简体   繁体   English

Java-While循环不会退出

[英]Java - While loop will not exit

//Loop that isn't working. //无效的循环。 I keep pressing a number that is 1,2,3,4, or 5 but it won't exit the loop. 我一直按1,2、3、4或5,但不会退出循环。 The operator seems to be assigned the value that I input but it still will not exit the while loop. 该操作员似乎被分配了我输入的值,但仍不会退出while循环。 I'm trying to write a basic calculator with simple math operations but this turned into a very annoying problem. 我试图用简单的数学运算编写一个基本的计算器,但这变成了一个非常烦人的问题。

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();
        }
    }
}

You loop conditional is the problem. 您循环条件是问题所在。

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

It should be 它应该是

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

Basically, you're saying that if the operator is != 1, then do the loop. 基本上,您是说如果运算符为!= 1,则执行循环。 Likewise each of the others. 同样,其他每个人。 If you were to utilize && operators instead of || 如果要使用&&运算符代替|| it would work much better. 它会好得多。

Really, what you want to say is that operator is > 1 && < 5, then loop, otherwise break. 确实,您要说的是运算符> 1 && <5,然后循环,否则中断。

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

Think about it logically, you want any number less than 1 OR greater than 5 to loop again. 从逻辑上考虑一下,您希望小于1或大于5的任何数字再次循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM