如何循环用户输入直到达到总和?

时间:2015-04-01 02:14:51

标签: java loops payment

我是Java和StackOverflow的新手(所以我希望这个问题和答案都不会在这里发布)。我正在为自动售货机编写代码,我需要创建一个循环,以便它继续询问用户输入,直到达到项目的成本。我该怎么做呢?

        System.out.println("Please enter payment of: $" + totalCost); // asking client to pay amount
    double pay1; // this is the name given to the first value of money the client enters
    pay1 = keyboard.nextInt();
        if (pay1 > totalCost) {
      System.out.println("You entered: $" + pay1);
      System.out.println("Change needed: $" + (pay1 - totalCost));
    }   else {
      System.out.println("You entered: $" + pay1);
      System.out.println("Please enter payment of: $" + (totalCost - pay1));
            }
    double pay2; // next value of money input by customer
    pay2 = keyboard.nextInt();
    double totalPaid = (pay1 + pay2);
    if (totalPaid > totalCost) {
      System.out.println("You entered: $" + pay2);
      System.out.println("Change needed: $" + (totalPaid - totalCost));
  } else {
      System.out.println("You entered: $" + pay2);
      System.out.println("Please enter payment of: $" + (totalCost -          totalPaid));
    }
    }
    }

1 个答案:

答案 0 :(得分:1)

你能更具体一点吗?伪代码可能如下所示:

while(money < desiredMoney) {
    askForMoney();
}