一直试图使一个简单的计算器加,减,除,乘。但这不允许我进入计算部分。即使我输入+,-,/或“如何让扫描仪理解输入的+,-,/”,它始终会显示“计算类型不正确”?谢谢
import java.util.Scanner;
public class Calculator {
public void typeOfCalc(){
Scanner user_input = new Scanner(System.in);
System.out.print("What type of calculation do you want? \n Addition? type '+' \n Subtraction? type '-' \n Division? type '/' \n or Multiplication type '*' \n");
String calcType = user_input.next().trim();
if (calcType != "+" || calcType != "*" || calcType != "/" || calcType != "-"){
System.out.println("Incorrect type of calculation, try again \n");
typeOfCalc();
}
else if (calcType == "+"){
System.out.print("Chose your first number \n");
int num1 = user_input.nextInt();
System.out.print("Chose your second number \n");
int num2 = user_input.nextInt();
System.out.print(num1 + " + " + num2 + " = \n" + (num1 + num2) + "\n");
}
else if (calcType == "-"){
System.out.print("Chose your first number \n");
int num1 = user_input.nextInt();
System.out.print("Chose your second number \n");
int num2 = user_input.nextInt();
System.out.print(num1 + " - " + num2 + " = \n" + (num1 - num2) + "\n");
}
else if (calcType == "/"){
System.out.print("Chose your first number \n");
int num1 = user_input.nextInt();
System.out.print("Chose your second number \n");
int num2 = user_input.nextInt();
System.out.print(num1 + " / " + num2 + " = \n" + (num1 / num2) + "\n");
}
else if (calcType == "*"){
System.out.print("Chose your first number \n");
int num1 = user_input.nextInt();
System.out.print("Chose your second number \n");
int num2 = user_input.nextInt();
System.out.print(num1 + " * " + num2 + " = \n" + (num1 * num2) + "\n");
}
}
}
最佳答案
一旦调整了代码以遵循@redFIVE的建议(用!=
替换!myVar.equals(str)
),请确保将AND(||
)替换为AND(&&
)。
考虑以下:if (!calcType.equals("+") || !calcType.equals("*") || ...)
如果输入为"+"
,则条件仍将通过,因为calcType
不等于"*"
,并且逻辑求值为TRUE。
当使用AND:if (!calcType.equals("+") && !calcType.equals("*") && ...)
时,您应该看到预期的结果。
但是,当前代码的主要问题是由于误用了!=
来比较Strings
。修复此问题,您至少可以使用调试器来查看上述逻辑为何会失败或产生意外结果。
关于java - 计算器不会接受用户输入,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34230650/