gpt4 book ai didi

java - 为我的 java 类做一个更改程序,不知道如何循环整个程序?

转载 作者:行者123 更新时间:2023-12-01 17:04:59 25 4
gpt4 key购买 nike

目前我正在开发一个程序,用户输入一个以美分为单位的值(因此 1.25 美元就是 125),程序确定以最少的金额给出多少个硬币。我有这个工作。

令我困扰的是,我的教授希望程序不断循环,直到用户输入小于 0 的值。我不知道如何执行此操作,因为每次我尝试时,它只会循环一次而不是循环显示适当数量的硬币。

请帮忙。

这是我的代码:

import java.util.Scanner;

public class MakingChange {

public static void main(String[] args) {
//Prompts user to input the change they recieved.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the amount of change you recieved in coin format. Example: $1.25 would be entered as 125.");
int Change = sc.nextInt(); //The value is then stored as an integer named Change.

int Pennies = 0;
int Nickels = 0;
int Dimes = 0;
int Quarters = 0;

while (Change < 1){
System.out.println("Error: Cannot enter a value less than 1!");
//System.exit(0); //found at http://codingforums.com/java-jsp/69296-%5Bjava%5D-how-end-program.html
}

while (Change > 0){ //Runs a loop which determines how many of each coin is used by subtracting the values of the largest first and continuing until 0.
if (Change >= 25){
Change -= 25;
Quarters++;
}
else if (Change >= 10){
Change -= 10;
Dimes++;
}
else if (Change >= 5){
Change -=5;
Dimes++;
}
else if (Change >= 1){
Change -= 1;
Pennies++;
}


}
System.out.println("In total, you should have recieved:");
System.out.printf("Number of Quarters: %3d %n", Quarters);
System.out.printf("Number of Dimes: %6d %n", Dimes);
System.out.printf("Number of Nickels: %4d %n", Nickels);
System.out.printf("Number of Pennies: %4d %n", Pennies);
//Prints out final number of coins used by type of coin.
}

}

最佳答案

废弃你的第一个 while 循环。您不希望两个循环处理同一件事。接下来,初始化“Change”变量,但将 sc.nextInt(); 移至内部,以便每次迭代都能获取输入。最后,使循环成为 do-while 循环,以便它至少运行一次(或者您可以将更改初始化为 1)。

int Change = 0;
do{
Change = sc.nextInt();
// ...
}
while(Change > 0);

关于java - 为我的 java 类做一个更改程序,不知道如何循环整个程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26110992/

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