我正在为我的Java类构建的更改机器出现问题。我对编程很新,所以这可能是一个愚蠢的逻辑错误。我的更改机器要求用户输入项目的价格然后支付金额,然后它应该计算用户将在季度,硬币等中收到多少变化......但是,它每次只计算1个季度。这是代码:
import java.util.Scanner;
import java.text.*;
public class Main {
public static void main(String[] args)
{
float penny = .1F, nickel = .5F, dime = .10F, quarter = .25F;
int pennyCtr = 0, nickelCtr = 0, dimeCtr = 0, quarterCtr = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Enter Purchase Price: ");
float price = scan.nextFloat();
DecimalFormat paidFormat = new DecimalFormat("0.00");
System.out.println("Enter Amount Paid: ");
float paid = scan.nextFloat();
float change = (float) (paid - price);
System.out.println("Your change from $" + paidFormat.format(paid)
+ " is: " + change);
if (change >= .25)
{
change -= quarter;
quarterCtr++;
}
else if (change < .25)
{
change -= dime;
dimeCtr++;
}
else if (change < .10)
{
change -= nickel;
nickelCtr++;
}
else if (change < .5)
{
change -= penny;
pennyCtr++;
}
System.out.println("Your change from $" + paidFormat.format(paid) +
" is: " + quarterCtr + " Quarters, " + dimeCtr + " Dimes, "
+ nickelCtr + " Nickles, " + pennyCtr + " Pennies. ");
System.out.println("Program written by Ashley ");
}
}
答案 0 :(得分:1)
一些一般提示:
while
循环。它应该循环多久?循环什么时候结束?double
代替您的声明和输入。答案 1 :(得分:0)
快速查看代码告诉我,你错过了这段代码之间的循环:
if (change >= .25)
{
change -= quarter;
quarterCtr++;
}
else if (change < .25)
{
change -= dime;
dimeCtr++;
}
else if (change < .10)
{
change -= nickel;
nickelCtr++;
}
else if (change < .5)
{
change -= penny;
pennyCtr++;
}
基本上,你的程序会在它将变化减少到0之前终止。这就是你每次只计算1枚硬币的原因。考虑可能是一个while循环(虽然改变&gt; 0)。