编写一个程序,重复读取一个0到100之间的整数,该整数表示分的个数。将美分的数目转换成相等的25美分、10美分、5美分和1美分的数目。程序应该输出最大数量的硬币,然后输出最大数量的硬币,以此类推。然后程序会询问下一笔金额。如果数量是负数,程序应该退出。
这就是我目前所拥有的,我不确定如何让它循环或计算数字或每个硬币。
System.out.println("Enter number of cents (Negative value to quit):");
int cents;
cents = scan.nextInt();
while (cents > 0 )
{
if (cents >= 25)
{
System.out.println("Quarter");
cents -= 25;
}
else if ( cents >= 10 )
{
System.out.println("Dime");
cents -= 10;
}
else if (cents >= 5 )
{
System.out.println("Nickle");
cents -= 5 ;
}
else if (cents >= 1 )
{
System.out.println("Penny");
cents -= 1;
}
}
您可以将问题分解为两部分:
do
询问金额而
金额非负1) 在主方法中询问输入
Scanner scan = new Scanner(System.in);
int input;
do {
input = scan.nextInt();
decompose(input);
} while (input > 0);
2)用另一种方法编写分解:
public static void decompose(int cents) {
if(cents >= 25) {
int quot = cents / 25;
System.out.println(quot + " Quarter");
cents -= quot * 25;
}
if(cents >= 10) {
int quot = cents / 10;
System.out.println(quot + " Dime");
cents -= quot * 10;
}
[...]
}
我的建议是使用散列表。您的代码可能看起来像这样:
System.out.println("Enter number of cents (Negative value to quit):");
Map<String, Long> countMap = HashMap<String, Long>();
countMap.put("Quarter", 0);
countMap.put("Dime", 0);
countMap.put("Nickle", 0);
countMap.put("Penny", 0);
int cents;
cents = scan.nextInt();
while (cents > 0 )
{
if (cents >= 25)
{
System.out.println("Quarter");
countMap.put("Quarter", countMap.get("Quarter")+1L);
cents -= 25;
}
else if ( cents >= 10 )
{
System.out.println("Dime");
countMap.put("Dime", countMap.get("Dime")+1L);
cents -= 10;
}
else if (cents >= 5 )
{
System.out.println("Nickle");
countMap.put("Nickle", countMap.get("Nickle")+1L);
cents -= 5 ;
}
else if (cents >= 1 )
{
System.out.println("Penny");
countMap.put("Penny", countMap.get("Penny")+1L);
cents -= 1;
}
}
现在你需要的都有了。
System.out.println("Quarter: " + countMap.get("Penny"));
System.out.println("Dime: " + countMap.get("Dime"));
System.out.println("Nickle: " + countMap.get("Nickle"));
System.out.println("Penny: " + countMap.get("Penny"));