一直在尝试制作一个简单的计算器加减乘除。但它不允许我进入计算部分。它总是说“计算类型不正确”,即使我键入 +、-、/或“” 我如何让扫描器理解 +、-、/、“”作为输入?谢谢
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");
}
}
}
最佳答案
您需要使用 .equals()
来检查字符串是否相等。
因此 calcType.equals("*")
用于相等性或 !calcType.equals("*")
用于检查它们是否相同。
字符串是不可变的,所以当你使用==
时,它是检查它是否是内存中的同一个字符串,而不是检查字符串的实际内容
关于java - 计算器不会接受用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34230650/