0

Here is my code:

public void checkOut() {   
    double sum;
    System.out.println("Checking out items ..."); 
    for (int i = 0; i < purchases.length; i++) {
        sum =+ purchases[i].getPrice();
        System.out.println(purchases[i].getDescription() + "/" + purchases[i].getPrice());
    }
    System.out.println("Amount due: " + "$" + new DecimalFormat("0.00").format(sum)); 
}

When I compile it I get this error:

The local variable sum may not have been initialized.

Alternatively when I change the sum line to double sum = sum + purchases[i].getPrice();

I get the following error:

sum cannot be resolved to a variable.


Its basically a method that takes the list of items placed in a shopping basket; prints the items and their individual price, then finds the total price (sum) of the items.

Can anyone please tell me what I'm doing wrong?

4

2 回答 2

9

Just initialize your variable:

double sum = 0.0;

In Java, a local method variable must be initialized before being used. In this case, you have just declared but not initialized your sum variable.

Note that the error is pretty descriptive: The local variable sum may not have been initialized. (emphasis mine).

Alternatively when I change the sum line to > double sum = sum + purchases[i].getPrice(); I get Error: sum cannot be resolved to a variable. (emphasis and syntax/grammar fixes mine).

This is because your sum variable is now inside the scope of the for loop and you're using it outside, which is wrong. The compiler is telling you that the sum variable has never been declared before so it can't use it.

This was the problem (template only):

for(...) {
    double sum = ...
}
//the compiler will complain asking what is this sum variable?
System.out.println(sum);

As stated in other answer, there is an error in your addition code. Fixing all that, your code will look like this:

public void checkOut(){   
    double sum = 0.0;
    System.out.println("Checking out items ..."); 
    for (int i = 0; i<purchases.length; i++) {
        sum += purchases[i].getPrice();
        System.out.println(purchases[i].getDescription() + "/" +
            purchases[i].getPrice());
    }
    System.out.println("Amount due: " + "$" +new DecimalFormat("0.00").format(sum)); 
}
于 2013-05-14T03:46:30.127 回答
4

您的变量sum需要初始化(0 很好;与 0.0 相同的字节码),但您也有一个严重的错误,您的编译器对您隐藏。你的意思不是说“总和=+”

而是使用,sum +=因为那是正确的加法赋值运算符。

请注意,它+=也会进行类型转换,所以它实际上比只做 a = a + b 更好。(对于那些老师不喜欢“神秘”代码的学生来说,这是一个很好的辩护+=,除了陈述 a = a + b 在数学上看起来如此可怕的错误。)

于 2013-05-14T03:50:31.720 回答