我正在学习java atm,并且必须编写代码来计算货币单位,并且仅使用单个单位的单数词和多个单位的复数词来显示非零面额。
这是到目前为止的代码:
import java.util.Scanner;
public class ComputeChange {
public static void main(String[] args) {
Scanner input = new Scanner(System. in );
// receive amount
System.out.println("Enter an amount in double, for example 11.56: ");
double amount = input.nextDouble();
int remainingAmount = (int)(amount * 100);
// find the number of one dollars
int numberOfDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
// find the number of quarters in the remaing amount
int numberOfQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
//find the number of dimes in the remaing amount
int numberOfDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
//find the number of nickels in the remaing amount
int numberOfNickles = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
//find the number of pennies in the remaining amount
int numberOfPennies = remainingAmount;
//Display results
System.out.println("Your amount" + amount + "consists of");
if (numberOfDollars > 1) {
System.out.println(" " + numberOfDollars + "dollars");
} else if (numberOfDollars == 1); {
System.out.println(" " + numberOfDollars + "dollar");
}
输出是: 运行:
Enter an amount in double, for example 11.56:
12,33
Your amount12.33consists of
12dollars
12dollar
1quarters
1quarter
0dimes
0dime
1nickles
1nickle
3pennies
3penny
为什么一切都打印出来? 3 ==不是1为什么它仍然说3便士? Noob问题可能,但那是因为我是一个:)感谢您的帮助!
答案 0 :(得分:4)
因为您在第二个;
之后添加了随机if
。因此,您的第二个System.out.println
不是if语句的一部分。删除它:
if (numberOfDollars > 1) {
System.out.println (" " + numberOfDollars + "dollars");
} else if (numberOfDollars == 1) {
System.out.println (" " + numberOfDollars + "dollar");
}
答案 1 :(得分:2)
在if();
if (numberOfDollars == 1);
第二个打印声明正在打印,因为if();
if()
的一部分
答案 2 :(得分:0)
替换
else if (numberOfDollars == 1); { // with ;, condition terminates here itself
与
else if (numberOfDollars == 1) {
在Statememnt结束时使用分号,以单行结束语句。意味着它忽略条件的结果并从下一行继续执行。