Java - While循环不会退出

时间:2015-09-29 02:07:51

标签: java loops while-loop

//循环不起作用。我一直按下1,2,3,4或5的数字,但它不会退出循环。操作符似乎被分配了我输入的值但它仍然不会退出while循环。我正在尝试用简单的数学运算编写一个基本的计算器,但这变成了一个非常讨厌的问题。

import java.util.Scanner;
public class BasicCalculatorTwo {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        int operator;
        double fnum, snum, answer;
        operator = 0;

        System.out.println("Enter first number : ");
        fnum = scanner.nextDouble();
        System.out.println("Enter second number : ");
        snum = scanner.nextDouble();

        while(operator != 1 || operator != 2 || operator != 3 || operator != 4 || operator != 5 ){
            System.out.println();
            System.out.println(fnum + " ? " + snum + " = ");
            System.out.println("1 : Add");
            System.out.println("2 : Subtract");
            System.out.println("3 : Multiply");
            System.out.println("4 : Divide");
            System.out.println("5 : Modularize");
            operator = scanner.nextInt();
        }

        switch(operator){
            case 1:
                answer = fnum + snum;
                break;
            case 2:
                answer = fnum - snum;
                break;
            case 3:
                answer = fnum * snum;
                break;
            case 4:
                answer = fnum / snum;
                break;
            case 5:
                answer = fnum % snum;
                break;
            default:
                break;
            System.out.println(fnum + " ? " + snum + " = " + answer);
            scanner.close();
        }
    }
}

1 个答案:

答案 0 :(得分:2)

循环条件是问题所在。

while (operator != 1 || operator != 2 || operator != 3 || operator != 4 || operator != 5)

应该是

while (operator != 1 && operator != 2 && operator != 3 && operator != 4 && operator != 5)

基本上,你说如果操作符是!= 1,那么就进行循环。同样,每个人都是如此。如果你要利用&&运算符而不是||它会工作得更好。

真的,你想说的是运营商是> 1&& < 5,然后循环,否则打破。

while(operator < 1 || operator > 5)
{
  DoPrintStuffHere();
}

从逻辑上考虑,您希望任何小于1或大于5的数字再次循环。