为什么这个 Java 在代码创建无限循环时执行?

Why does this Java do while code create an infinite loop?

我想弄清楚为什么我的 do while 循环给我留下了一个无限循环,我无法继续前进,尽管从逻辑上讲,对我来说它似乎应该有效。这是有问题的代码:

public void enterData(){ 
        System.out.println("Polish Notation Calculator");
    do{
        System.out.print("Please enter an operation: ");
        oper = input.next().charAt(0);
    }while (oper != '+' || oper != '*' || oper != '/' || oper != '-' || oper != '%');
        System.out.print("First number: ");
        x = input.nextDouble();
        System.out.print("Second number: ");
        y = input.nextDouble(); 

据我所知,这个循环说的只是执行打印和扫描功能,而 oper 不等于引号中的任何内容。为什么这不起作用?

因为你的条件总是正确的。替换||用 &&.

或者您可以改写为:

while (!(oper == '+' || oper == '*' || oper == '/' || oper == '-' || oper == '%'))

逻辑上等同于:

while (oper != '+' && oper != '*' && oper != '/' && oper != '-' && oper != '%')

换句话说:

NOT(A = X || A = Y)

等同于:

A != X && B != Y

或者你使用KISS原则:

while (true) {
    System.out.print("Please enter an operation: ");
    oper = input.next().charAt(0);

    if ("+*/-%".indexOf(oper) != -1) {
        break;
    }
}

或者你使用decomposition:

do {
    System.out.print("Please enter an operation: ");
    oper = input.next().charAt(0);
} while (!isValidOperation(oper));

...

public boolean isValidOperation(char oper) {
    return oper == '+' || oper == '*' || oper == '/' || oper == '-' || oper == '%';
}

替换

while (oper != '+' || oper != '*' || oper != '/' || oper != '-' || oper != '%');

while (oper != '+' && oper != '*' && oper != '/' && oper != '-' && oper != '%');

目前,您的条件始终为真。

为了退出循环,操作员在第

行输入
oper = input.next().charAt(0);

必须不同于 '+', '-', '*', '/''%'。如果输入这些字符中的任何一个,循环将重复。显然,这就是你在做的事情。

因此,一个明显的解决方案是将 while 子句的 || 操作数替换为 &&

另一种解决方案是使用 switch 语句,它更具可读性(也更快):

boolean loop = true;
do {
  System.out.print("Please enter an operation: ");
  oper = input.next().charAt(0);
  switch (oper) {
    case '+':
    case '-':
    case '*':
    case '/':
    case '%':
      loop = false;
      break;
} while (loop);