我目前正在制作一个能够找到数字百分比的项目。但是,当我根据用户输入创建if语句来确定要执行的进程时,即使输入与if语句匹配,它也会跳到最后的else语句。这是我的代码。
public class Percentage {
public static void main (String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter 'a' if you want to find a percentage of a given number.");
System.out.println("Enter 'b' if you want to find how much percent of a given number is a certain number.");
String choice = input.nextLine();
if (choice == "a"){
System.out.println("Enter the number.");
float numA = input.nextFloat();
System.out.println("Enter what percentage of the number you want to find.");
float perA = input.nextFloat();
float decA = perA * 0.01F;
float outA = numA * decA;
System.out.println(perA + "% of" + numA + "is: " + outA);
} else if (choice == "b"){
System.out.println("Enter the main number.");
float mainB = input.nextFloat();
System.out.println("Enter the number whose percentage of the main number you want to find.");
float minB = input.nextFloat();
float quoB = minB/mainB;
float perB = quoB * 100;
System.out.println(minB + "is" + perB + "% of " + mainB);
} else {
System.out.println("Invalid answer.");
}
input.close();
}
}
当我运行程序并输入a或b时,它直接转到else语句输出"无效答案。"我的代码有什么问题?