我是java的新手,我决定编写一个简单的程序来练习IF。这是它应该做的:
以下是代码:
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”。然后,我读了this并添加了“sc.nextLine()”。然而,该程序只是忽略了最后的if和不打印任何东西。关于导致问题的原因以及如何解决问题的任何想法?
p.s。:这是我在运行程序时得到的结果:
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
答案 0 :(得分:1)
请尝试
if (Confirm.equals("y")){
和
else if (Confirm.equals("n"))
使用==
比较对象引用而不是值。
答案 1 :(得分:1)
尝试equals
代替==
,一次应为sc.nextLine();
Confirm = sc.nextLine();
if (Confirm.equals("y")){
而不是
sc.nextLine();
Confirm = sc.nextLine();
if (Confirm=="y"){