我是 Java 新手,我决定编写一个简单的程序来练习 IF。这是它应该做的:
- 向用户询问货币。
- 询问用户他想要转账的金额。
- 计算佣金率并向用户显示详细信息。
- 要求用户确认;如果他键入“y”,程序应该打印“A”。如果他键入“n”,程序应该打印“B”。
这是代码:
import java.util.Scanner;
public class CommissionRate {
static String Confirm;
static byte CommissionRate=10;
static String Commission="1%.";
static double TotalCost;
static double MoneyAmount;
static byte CurrencyNum;
static char CurrencySign;
static Scanner sc = new Scanner(System.in);
public static void Currency(){
System.out.println("Please choose your desired currnecy.");
System.out.println("1.USD");
System.out.println("2.EUR");
System.out.println("3.GBP");
System.out.println("4.CAD");
System.out.println("5.CNY");
System.out.println("6.JPY");
CurrencyNum = sc.nextByte();
if (CurrencyNum==1|CurrencyNum==4) {
CurrencySign= '$';
}
else {
if (CurrencyNum==2){
CurrencySign='€';
}
else {
if (CurrencyNum==3){
CurrencySign='£';
}
else {
if (CurrencyNum==5|CurrencyNum==6){
CurrencySign='¥';
}
}
}
}
}
public static void MoneyAmount() {
System.out.println("Please enter the amount of money you would like to transfer :");
MoneyAmount = sc.nextDouble();
if (MoneyAmount>499 & MoneyAmount<10000){
CommissionRate=5;
Commission="0.5%.";
}
else{
if (MoneyAmount>10000){
CommissionRate= 3;
Commission="0.3%.";
}
}
TotalCost = MoneyAmount + MoneyAmount * CommissionRate/1000;
System.out.println("Please confirm the transfer. ( y/n ) ");
System.out.println("A transfer of "+MoneyAmount+CurrencySign+".");
System.out.println("Commission rate is "+Commission);
System.out.println("You need to pay " + TotalCost+"." );
sc.nextLine();
Confirm = sc.nextLine();
if (Confirm=="y"){
System.out.println("A");
}
else if (Confirm=="n") {
System.out.println("B");
}
}
}
起初,程序不会等待用户确认/中止传输,它会打印“B”。然后,我阅读并添加了“sc.nextLine()”。然而,该程序只是忽略了最后一个 if 并且不打印任何内容。关于导致问题的原因以及如何解决问题的任何想法?
ps:这是我运行程序时得到的:
Please choose your desired currnecy.
1.USD
2.EUR
3.GBP
4.CAD
5.CNY
6.JPY
2 // my input
Please enter the amount of money you would like to transfer :
120 // my input
Please confirm the transfer. ( y/n )
A transfer of 120.0€.
Commission rate is 1%.
You need to pay 121.2.
y // my input