試圖在用戶輸入6個數字的情況下創建for循環。然後驗證每個數字以確定它是否爲正數。然後他們全部加起來作爲小計。本地變量可能尚未在我的For循環中初始化
在我的最後一行count += itemPrice;
我在count
上發生錯誤,提示「局部變量可能未被初始化。」我的一個好友似乎無法弄清楚爲什麼,並想知道那是怎麼回事。
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;
}
你需要給你的計數默認值。在這裏,我建議0. – realUser404 2014-12-01 21:11:40
你的方法需要一個'count'上的return語句需要一個默認值。 – 2014-12-01 21:13:06
可能的重複[如何避免'局部變量可能未被初始化'?](http://stackoverflow.com/questions/1585513/how-to-avoid-the-local-variable-may-not-have -been-initialized) – 2014-12-01 21:13:50