本文介绍了可能尚未在我的For循环中初始化局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试在用户输入6个数字的位置进行for循环。然后验证每个数字以确定它是正数。然后他们都加起来进行小计。
Trying to make a for loop where a user inputs 6 numbers. Then each number is validated to see that it is positive. Then they are all added up for a subtotal.
在我的最后一行 count + = itemPrice;
我是在 count上收到错误
说本地变量可能尚未初始化。我的一个伙伴似乎也无法弄清楚原因,并想知道是什么原因。
On my last line count += itemPrice;
I'm getting an error on count
saying "The local variable may not have been initialized." A buddy of mine can't seem to figure out why as well and wondering what is up with that.
public static double namehere() {
double count;
for (int x = 0; x < 6; x++)
{
Scanner input = new Scanner (System.in);
System.out.println ("Price of Item: ");
double itemPrice = input.nextDouble();
while (itemPrice < 0.01)
{
Scanner input2 = new Scanner (System.in);
System.out.println ("Price of Item: ");
itemPrice = input.nextDouble();
}
count += itemPrice;
}
推荐答案
double count; // not initialized
double count = 0; // initialized
默认情况下,本地原始变量不设置为0,因此必须显式初始化它们。
Local primitive variables are not set to 0 by default, so they must be explicitly initialized.
这篇关于可能尚未在我的For循环中初始化局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!