gpt4 book ai didi

java - 如何要求多个输入并在用户输入 0 时停止?

转载 作者:行者123 更新时间:2023-11-29 07:04:42 26 4
gpt4 key购买 nike

我的程序应该接收大量的钱,并将其转换为零钱,但是当它接收到 0 时,它应该停止请求输入并停止程序。

我所有的数学都正确,我只是在重复询问数字时遇到问题。这是我目前拥有的:

public class Coins {

public static int quarters;
public static int dimes;
public static int nickels;
public static int pennies;

public static int Quarters(int TotalCoins) {
quarters = (int) (TotalCoins / 25);
TotalCoins %= 25;
return quarters;
}
public static int Dimes(int TotalCoins){
TotalCoins -= (quarters * 25);
dimes = (int) (TotalCoins / 10);
TotalCoins %= 10;
return dimes;
}
public static int Nickels(int TotalCoins){
TotalCoins -= (dimes * 10) + (quarters * 25);
nickels = (int) (TotalCoins / 5);
TotalCoins %= 5;
return nickels;
}
public static int Pennies(int TotalCoins){
TotalCoins -= (nickels * 5 ) + (dimes * 10 ) + (quarters * 25);
pennies = (int) (TotalCoins / 1);
TotalCoins %= 1;
return pennies;
}
}

这是我的测试类(我很确定我的主要问题是):

public class CoinsTester {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);

if (kybd.nextInt() != 0){
int changeMoney = kybd.nextInt();
System.out.println("Quarters = " + Coins.Quarters(changeMoney) + "\nDimes = " + Coins.Dimes(changeMoney) + "\nNickels = " + Coins.Nickels(changeMoney) + "\nPennies = " + Coins.Pennies(changeMoney));
}
}
}

任何帮助都会很棒。

编辑:有人告诉我,在一节课中完成所有事情可能会更容易,如果是这样,那么以这种方式进行的任何建议也将非常出色。谢谢你!!!
编辑:我忘了提到我应该能够输入所有数字然后显示所有数字的输出。

最佳答案

你想要这样的东西:

Scanner kybd = new Scanner(System.in);

while (true) {
int changeMoney = kybd.nextInt();
if (changeMoney == 0)
break;

// do stuff with changeMoney
}

也可以表示为一个for循环:

Scanner kybd = new Scanner(System.in);
for (int changeMoney = kybd.nextInt(); changeMoney != 0; changeMoney = kybd.nextInt()) {
// do stuff with changeMoney
}

虽然行数较少,但它使 for 循环行相当长,但可以通过使用较短的变量名来缓解这一问题:

Scanner in = new Scanner(System.in);
for (int i = in.nextInt(); i != 0; i = in.nextInt()) {
// do stuff with i
}

关于java - 如何要求多个输入并在用户输入 0 时停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21176216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com