java - How to add together elements of an Array List -
so i'm trying make cash register program takes in array of integer prices , adds them total sale price. here's snippet of code that's important
do { system.out.print("enter integer price: $ "); int = in.nextint(); prices.add(i); system.out.println(); } while(in.hasnextint()); for(int i=0; i<prices.size(); i++) { int total = prices.get(i) + prices.get(i+1); } system.out.println(total);
my error says "total cannot resolved variable" , earlier didn't when tried make increment in loop i+2 instead of i++. can have no idea how add these variables
is right track?
for(int i=0; i<prices.size(); i++) { int total = 0; int total = total + prices.get(i); }
you're doing 2 things wrong here:
int total = prices.get(i) + prices.get(i+1);
you're declaring total
inside for
loop. outside default value of 0
. adding values of current iteration , next iteration. want total = total + prices.get(i);
or total += prices.get(i);
.
preferably, can values. there's no need additional list prices
:
int total = 0; { system.out.print("enter integer price: $ "); int = in.nextint(); total += i; //prices.add(i);//if still want keep list system.out.println(); } while(in.hasnextint()); system.out.println(total);
Comments
Post a Comment