java - Cannot get a sum from a for loop -
here code:
public void checkout() { double sum; system.out.println("checking out items ..."); (int = 0; < 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 compile error:
the local variable sum may not have been initialized.
alternatively when change sum line double sum = sum + purchases[i].getprice();
i following error:
sum cannot resolved variable.
method takes list of items placed in shopping basket; prints items , individual price, finds total price (sum) of items.
can please tell me i'm doing wrong?
just initialize variable:
double sum = 0.0;
in java, local method variable must initialized before being used. in case, have declared not initialized sum
variable.
note error pretty descriptive: the local variable sum
may not have been initialized. (emphasis mine).
alternatively when change sum line >
double sum = sum + purchases[i].getprice();
error: sum cannot resolved variable. (emphasis , syntax/grammar fixes mine).
this because sum
variable inside scope of for
loop , you're using outside, wrong. compiler telling sum
variable has never been declared before can't use it.
this problem (template only):
for(...) { double sum = ... } //the compiler complain asking sum variable? system.out.println(sum);
as stated in other answer, there error in addition code. fixing that, code this:
public void checkout(){ double sum = 0.0; system.out.println("checking out items ..."); (int = 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)); }
Comments
Post a Comment