为什么我的代码会直接跳到else语句?如果询问,它会返回正确输入的值。但无法弄清楚为什么它只是跳到“错误!”而不是进入相关的计算器。这是我的代码:
package easy2;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
float force, mass, acc;
String answer = null;
Scanner in = new Scanner(System.in);
System.out.println("Force = Mass x Acceleration Calculator");
System.out.println("Please state which variable you wish to work out: force, mass or acceleration");
answer = in.nextLine();
if(answer == "force"){
System.out.println("What is your mass in killograms?");
mass = in.nextFloat();
System.out.println("What is your acceleration in meters per second?");
acc = in.nextFloat();
force = mass * acc;
System.out.println("The force of this equation in Netwon Meters is " + force);
}
else if(answer == "mass") {
System.out.println("What is your force in Newton Meters?");
force = in.nextFloat();
System.out.println("What is your acceleration in meters per second?");
acc = in.nextFloat();
mass = force / acc;
System.out.println("The mass of this equation is equal to " + mass + "kg");
}
else if(answer == "acceleration"){
System.out.println("What is your force in Newton Meters?");
force = in.nextFloat();
System.out.println("What is your mass in killograms?");
mass = in.nextFloat();
acc = force / mass;
System.out.println("The acceleration of this equation equals " + acc + "m/s");
}
else{System.out.println("ERROR!");
}
}
}
答案 0 :(得分:2)
尝试使用myString.equals("myOtherString")
。你错误地进行了字符串比较。
==
是比较对象的相等性,而不是它们的值。
我无数次犯了同样的错误。