Java 错误的异常处理?程序不断循环?

Java 错误的异常处理?程序不断循环?,java,Java,因此,我目前正在处理这个问题[请记住,我删掉了大部分代码,因为它相当长] int choice = 0; while (choice != 7){ System.out.println("--- Mathematical Calculator ---"); System.out.println(""); System.out.println("Pick an operation from the list - Use nos. 1 to 7");

因此,我目前正在处理这个问题[请记住,我删掉了大部分代码,因为它相当长]

    int choice = 0;
    while (choice != 7){ 

    System.out.println("---  Mathematical Calculator  ---");
    System.out.println("");
    System.out.println("Pick an operation from the list - Use nos. 1 to 7");
    System.out.println("1) Multiplication");
    System.out.println("2) Division");
    System.out.println("3) Addition");
    System.out.println("4) Subtraction");
    System.out.println("5) Find the area of a regular object");
    System.out.println("6) Find the volume of a regular object");
    System.out.println("7) Exit Program");  

    **boolean ok = false;
    do {
        try{
            choice = userInput.nextInt();
            ok = true;
        } catch (InputMismatchException e){
                System.out.println("Invalid input");
                    }
    }
    while (ok = false);**

    switch (choice) {

    case 1:

    case 2: 

    case 3:

    case 4:

    case 5:

    case 6:



 case 7:            
System.out.println("Thanks for using my program"); 
            System.out.println("Program terminated");
            break; 





    default: System.out.println("Invalid choice");

        }

    }
    userInput.close();
}
因此,当前,当我运行程序并输入非整数的内容时,程序将给出以下输出:

---  Mathematical Calculator  ---

Pick an operation from the list - Use nos. 1 to 7
1) Multiplication
2) Division
3) Addition
4) Subtraction
5) Find the area of a regular object
6) Find the volume of a regular object
7) Exit Program
Invalid input
Invalid choice

Over
And over
And over
我知道我可能在异常处理方面做了一些错误(程序在有效输入下运行良好),但我真的不知道如何修复它

帮助?

while(ok=false)应该是
while(ok==false),或(!ok)时的

ok=false
是一个赋值

另外,我猜你是故意让箱子空着的,但即便如此,还是要确保你放了一个
break在每个选项上,否则将始终执行选项7

编辑:对于无限循环,您还应该执行Kevin Esche在(+1)中的建议。

while(ok=false)应该是
while(ok==false),或(!ok)时的

ok=false
是一个赋值

另外,我猜你是故意让箱子空着的,但即便如此,还是要确保你放了一个
break在每个选项上,否则将始终执行选项7


编辑:对于无限循环,您还应该按照Kevin Esche在(+1)中的建议进行操作。

您需要在异常中使用
userInput.nextLine()
捕捉\n\r,它将永远停止打印

catch (InputMismatchException e){
       System.out.println("Invalid input");
       userInput.nextLine();
}

您需要在异常中使用
userInput.nextLine()
捕获\n\r,它会像这样永远停止打印

catch (InputMismatchException e){
       System.out.println("Invalid input");
       userInput.nextLine();
}

什么是双星号?复制粘贴问题?或者试图用黑体字来表示?什么是双星号?复制粘贴问题?还是试图用黑体字写这一块?成功了。我试着放一个nextInt();这不起作用,谢谢你的反馈。起作用了。我试着放一个nextInt();这不起作用,谢谢你的反馈。是的,你们两个都是对的……至于案件,是的,我确实放了一个假。是的,你们两个都是对的……至于案件,是的,我放了一个假。