【发布时间】:2014-09-30 00:38:25
【问题描述】:
目前我正在开发一个程序,在该程序中用户输入一个以美分为单位的值(因此 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.
}
}
【问题讨论】:
标签: java loops if-statement while-loop java.util.scanner