参见英文答案 > How do I compare strings in Java? 23个
所以我仍然试图让这个计算器正常工作.重点在于它一直要求y值和操作符,直到用户输入“q”.唯一的事情是它不会返回值,一旦我输入q它就不会停止.它只是在事后要求y值.下面是我不断得到的输出的一个例子.我是否必须创建一个额外的变量来保存y值以更新它并在之后将其打印出来?
X:5 Y:5 Op:Y:5 Op:q Y:
Scanner keyboard = new Scanner(System.in);
double x;
double y;
String Op;
System.out.print("X: ");
x = keyboard.nextDouble();
do{
System.out.print("Y: ");
y = keyboard.nextDouble();
keyboard.nextLine();
System.out.print("Op: ");
Op = keyboard.nextLine();
if(Op == "+"){
double result = sum(x,y);
System.out.println(result);
}
else if(Op == "/"){
double division = div(x,y);
System.out.println(division);
}
else if(Op == "-"){
double subtraction = sub(x,y);
System.out.println(subtraction);
}
else if(Op == "*"){
double times = mult(x,y);
System.out.println(times);
}
else if(Op == "q")
System.out.print("Your last result was: " +y);
}while(Op != "q");
}
public static double sum (double a, double b){
double res = a + b;
return res;
}
public static double div (double a, double b){
if(b==0){
System.out.println("Error, attempted a division by zero");
return b;
}
double divide = a/b;
return divide;
}
public static double sub (double a, double b){
double minus = a-b;
return minus;
}
public static double mult (double a, double b){
double times = a*b;
return times;
}
}
解决方法:
对于字符串比较,您需要使用方法equals或equalsIgnoreCase.
==运算符仅适用于char,int,byte等基元.对于String等对象,需要使用比较方法.
转换为正确的方法将解决您的问题.例
if (Op.equalsIgnoreCase("q")){
...
}