为什么我的程序在条件为假时进入while循环?

Maj*_*tic 1 java if-statement while-loop polish-notation

当我输入字符串运算符时,无论是加法(+),减法( - ),乘法(*),除法(/)还是模块(%),即使输入有效输入,它仍会进入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));

    }

}
Run Code Online (Sandbox Code Playgroud)

小智 5

如果你用英语写你的布尔选择,它会读"当运算符不等于"+"或它不等于" - 或它不等于"/"或它不等于"*"或它不等于" %"做循环.

你需要它说"虽然操作符不等于"+"它不等于" - "它不等于"/"它不等于"*"它不等于"%"做循环.

改变|| 到&&它应该工作

要制定一个while循环,所有参数都必须为true.因此,如果其中一个参数为false,则while循环不会激活.