问题:编写一个创建两个并行数组的程序。第一个是字符串数组,其中包含购物清单中的项目名称。第二个是每个项目的价格数组。必须满足以下条件:
0
退出时,打印到期金额。 我真的很困惑数组,而且我在计算总数时遇到了麻烦。任何帮助是极大的赞赏。
这是我到目前为止所拥有的......
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Items on the list");
String[] list = {"eggs", "milk", "chicken", "cereal"};
double[] prices = {2.00, 2.50, 4.50, 1.00};
for (int i = 0; i < 4; i++) {
System.out.println((i + 1) + ". " + list[i] + " " + prices[i]);
}
System.out.println("What item do you 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 you like another 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;
}
}
}
答案 0 :(得分:0)
System.out.println( "What do you want?" );
int item = in.nextInt();
double total = 0;
while( item != 0 )
{
System.out.println( "How many?" );
int quant = in.nextInt();
// below is equiv to total += prices[item-1] * quant;
total = total + (prices[item-1] * quant); // add to the total
// initially it is 0, so after the first
// iteration it is the cost of the first item*quantity.
// and then keeps adding the new item*quantity to it.
// notice this is done at the end of the loop so that the next statement that
// gets executed is whether to continue or not.
System.out.println( "Which item?" );
item = in.nextInt();
}
答案 1 :(得分:0)
开头看起来是正确的,但你把while循环弄乱了一点。我只是做了一个方法来向你展示它应该是什么样子(未经测试):
double total = 0;
do {
System.out.println("What item do you want?");
int item = in.nextInt();
if (item == 0)
break;
System.out.println("How many do you want?");
int quantity = in.nextInt();
total += quantity * prices[item - 1];
} while(true);
System.out.println("You have to pay " + total);