当我输入一个字符串运算符时,无论是加法(+)、减法(-)、乘法(*)、除法(/)还是模块(%),即使我输入了有效的输入,它仍然会进入 while 循环。我不知道问题出在哪里,因为 while 循环工作正常,我必须为变量 num2 输入一个 int 值。
import java.util.Scanner;
public class PolishNotationCalc {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num1;
int num2;
String operator;
System.out.println("Polish notation calculator");
System.out.print("Please enter an operation(+, -, *, /, %) ");
operator = input.nextLine();
while (!operator.equals("+") || !operator.equals("-") || !operator.equals("*") || !operator.equals("/") || !operator.equals("%")) {
System.out.println("Please enter a valid operation ");
operator = input.nextLine();
if (operator.equals("+") || operator.equals("-") || operator.equals("*") || operator.equals("/") || operator.equals("%"))
break;
}
System.out.print("");
System.out.print("Please enter the first number ");
num1 = input.nextInt();
System.out.print("Please enter the second number ");
num2 = input.nextInt();
while (num2 == 0 && operator.equals("/")) {
System.out.println("Please pick a non zero number: ");
num2 = input.nextInt();
}
while (num2 == 0 && operator.equals("%")) {
System.out.println("Please pick a non zero number: ");
num2 = input.nextInt();
}
if (operator.equals("+"))
System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
else if (operator.equals("-"))
System.out.println(num1 + " - " + num2 + " = " + (num1 - num2));
else if (operator.equals("*"))
System.out.println(num1 + " * " + +num2 + " = " + (num1 * num2));
else if (operator.equals("/"))
System.out.println(num1 + " / " + num2 + " = " + (num1 / num2));
else if (operator.equals("%"))
System.out.println(num1 + " % " + num2 + " = " + (num1 % num2));
}
}