如何保持阵列的总数?

时间:2014-03-21 20:40:31

标签: java arrays

问题:编写一个创建两个并行数组的程序。第一个是字符串数组,其中包含购物清单中的项目名称。第二个是每个项目的价格数组。必须满足以下条件:

  1. 使用价格打印第一个数组中的编号项目列表。
  2. 要求用户选择一个项目并指定数量。
  3. 跟踪他们购物的总计。
  4. 当他们输入0退出时,打印到期金额。
  5. 我真的很困惑数组,而且我在计算总数时遇到了麻烦。任何帮助是极大的赞赏。

    这是我到目前为止所拥有的......

     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;
        }
    }
    

    }

2 个答案:

答案 0 :(得分:0)

啊,你太近了。您无需跟踪2个项目,只需一个项目。此外,您希望每次迭代添加总计,而不是完全覆盖它。目前,您的总变量包含第一项*数量加上输入的 last 项的价格。

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);