我是java和编程的新手
有人可以建议可以使用什么,以便答案必须等于+,-,*,/ ?
目前我正在尝试创建一个if语句,但我收到一个错误,我不太清楚为什么。有人可以查看我的代码并帮我完成if语句吗?如果您对可以改进的内容有任何其他建议,请分享。
import java.util.Scanner;
public class Calculator {
public static void main (String Args []) {
Scanner input = new Scanner(System.in);
double firstNumber, secondNumber;
String equationOperator;
System.out.println("Please give your first number: \t");
firstNumber = input.nextDouble();
System.out.println("Please give your second number: \t");
secondNumber = input.nextDouble();
System.out.println("Which equation would you like to perform?");
System.out.println("Please enter one of the following + - / * \t");
equationOperator = input.next();
switch (equationOperator) {
case "+":
System.out.println("Your chosen equation is: Adding");
System.out.println("Your answer is: " + (firstNumber + secondNumber));
break;
case "-":
System.out.println("Your chosen equation is: Subtracting");
System.out.println("Your answer is: " + (firstNumber - secondNumber));
break;
case "/":
System.out.println("Your chosen equation is: Dividing");
System.out.println("Your answer is: " + (firstNumber / secondNumber));
break;
case "*":
System.out.println("You chosen equation is: Multiplying");
System.out.println("Your answer is: " + (firstNumber * secondNumber));
break;
}
if (!equationOperator.equals("+ || - || / || *") {
System.out.println("Please choose one of the following:");
System.out.println("+"
+ "-"
+ "/"
+ "*");
}
System.out.println("\t Thank You for using my Calculator");
}
}
答案 0 :(得分:4)
您在条件中错过了一个右括号:
if (!equationOperator.equals("+ || - || / || *") {
应该是
if (!equationOperator.equals("+ || - || / || *")) {
请注意,这不会给您预期的结果,因为您正在检查完全字符串" + || - || / || *
"。
您需要多个equals
,例如
if (!equationOperator.equals("+") && !equationOperator.equals("-") ...) {
或仅在default
声明中使用switch
案例:
switch (equationOperator) {
case "+":
System.out.println("Your chosen equation is: Adding");
System.out.println("Your answer is: " + (firstNumber + secondNumber));
break;
case "-":
System.out.println("Your chosen equation is: Subtracting");
System.out.println("Your answer is: " + (firstNumber - secondNumber));
break;
case "/":
System.out.println("Your chosen equation is: Dividing");
System.out.println("Your answer is: " + (firstNumber / secondNumber));
break;
case "*":
System.out.println("You chosen equation is: Multiplying");
System.out.println("Your answer is: " + (firstNumber * secondNumber));
break;
default:
System.out.println("Please choose one of the following:");
System.out.println("+"
+ "-"
+ "/"
+ "*");
}
当其他任何一个匹配时,将执行default
个案。有关详细信息,请参阅the documentation。
答案 1 :(得分:1)
在开关
中使用默认大小写default:
System.out.println("Please choose one of the following:");
System.out.println("+"
+ "-"
+ "/"
+ "*");
}
此外,你的if语句不正确,除了支架从最后丢失。
if(!equationOperator.equals(“+ || - || / || *”))这将您的equationOperator与字符串“+ || - || / || *”进行比较。
你想要这个
if(!(equationOperator.equals(“+”)|| equationOperator.equals(“ - ”)|| equationOperator.equals(“/”)|| equationOperator.equals(“*”))){