java - How to keep a total with an array? -
question: write program creates 2 parallel arrays. first string array contains names of items in grocery list. second array of prices each item. must satisfy following conditions:
- print numbered list of items in first array prices.
- ask user select item , specify quantity.
- keep track of running total shopping.
- when enter
0
exit, print total amount due.
i'm confused arrays, , having trouble calculating total. appreciated.
here's have far...
public static void main(string[] args) { scanner in = new scanner(system.in); system.out.println("items on list"); string[] list = {"eggs", "milk", "chicken", "cereal"}; double[] prices = {2.00, 2.50, 4.50, 1.00}; (int = 0; < 4; i++) { system.out.println((i + 1) + ". " + list[i] + " " + prices[i]); } system.out.println("what item want"); int item1 = in.nextint(); system.out.println("what quantity"); int quantity1 = in.nextint(); double total1; double total2; double total = 0; while (item1 != 0) { system.out.println("would item"); int item2 = in.nextint(); if (item2 == 0) { system.out.println(total); break; } system.out.println("what quantity?"); int quantity2 = in.nextint(); total1 = (prices[item1 - 1] * quantity1); total2 = (prices[item2 - 1] * quantity2); total = total1 + total2; } }
}
ah, close. don't need keep track of 2 items, one. also, want add total each iteration, not overwrite it. currently, total variable contains price of first item * quantity plus last item entered.
system.out.println( "what want?" ); int item = in.nextint(); double total = 0; while( item != 0 ) { system.out.println( "how many?" ); int quant = in.nextint(); // below equiv total += prices[item-1] * quant; total = total + (prices[item-1] * quant); // add total // 0, after first // iteration cost of first item*quantity. // , keeps adding new item*quantity it. // notice done @ end of loop next statement // gets executed whether continue or not. system.out.println( "which item?" ); item = in.nextint(); }
Comments
Post a Comment