在 "while loop" 中使用 "try and catch " 块时无限循环

Endless loop while using "try and catch " block inside a "while loop"

当我在 while 循环.

中使用 try 和 catch 块时,我的程序出现了无限循环
import java.util.*;
class Try
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        while(true)
        {
            try {
                System.out.println("Enter a no ");
                int s=sc.nextInt();
            } catch(Exception e) {
                System.out.println("Invalid input try again");
            }
        }
    }
}

当我输入一个整数时,它运行良好并要求另一个输入,但是当我输入一个字符时,它进入无限循环。为什么会这样?

你没有打破循环。要结束循环,您需要插入

break;

您希望循环在何处结束。

当遇到无效输入时,您的程序会进入无限循环,因为 nextInt() 不会消耗无效标记。因此,导致异常的任何标记都将保留在那里,并在您下次尝试使用 nextInt() 时继续引发异常。

这可以通过在 catch 块中调用 nextLine() 来处理导致抛出异常的任何输入、清除输入流并允许用户继续尝试来解决。

扫描 int 不会消耗换行符(按回车键)。因此它每次都会读取换行符并抛出 InputMismatchException。

您只需在输入 之后调用next()nextLine() 即可使用它。

注意: next() 只适用于 unix,因为它只读取一个字节并且 Windows 以两个字符结束一行 (\r\n) .

问题是,当你调用nextInt时,你会搞砸Scanner,所以一旦nextInt出现异常,它就不能使用了。 Scanner 不再有效。为了解决这个问题,您应该将内容读取为 string 并进行转换,当转换操作失败时,您不必担心任何事情。

我会这样做:

import java.util.*;
class Try
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        while(true)
        {
            try{
                System.out.println("Enter a no ");
                int s=Integer.parseInt(sc.next()); // or sc.nextLine() if you wish to get multi digit numbers 
             }catch(Exception e)
               {
                 System.out.println("Invalid input try again");
               }
        }
    }
}

为了解决这个问题,您需要清除输入流,否则已经捕获的相同异常会导致无限循环。通过在 catch 块中添加 nextLine() 来消耗导致异常的任何输入 thrown.As 像这种情况这样的最佳实践最好在调用 nextInt()[ 之前使用 hasNextInt() 检查用户输入=11=]

import java.util.*;
class Try {
    public static void main(String args[]) {
        Scanner scanner=new Scanner(System.in);
        while(true) {
            try {
                System.out.println("Enter a Number");
                int num=scanner.nextInt();
            } catch(Exception e) {
                System.out.println("Invalid input try again");
                scanner.nextLine(); // cause to consume already caught Exception 
            }
        }
    }
}