使用“try and catch"时的无限循环“while循环"内的块 [英] Endless loop while using "try and catch " block inside a "while loop"

查看:35
本文介绍了使用“try and catch"时的无限循环“while循环"内的块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 while 循环中使用 try and catch 块时,我的程序有一个无限循环.

My program has an endless loop, when I use try and catch block in a while loop.

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

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

When I input an integer, it runs fine and asks for another input, but when I input a char, it goes for endless loop. Why is this so?

推荐答案

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

Your program enters an infinite loop when an invalid input is encountered because nextInt() does not consume invalid tokens. So whatever token that caused the exception will stay there and keep causing an exception to be thrown the next time you try to use nextInt().

这可以通过在 catch 块中放置一个 nextLine() 调用来解决任何导致抛出异常的输入,清除输入流并允许用户继续尝试.

This can be solved by putting a nextLine() call inside the catch block to consume whatever input was causing the exception to be thrown, clearing the input stream and allowing the user to continue trying.

这篇关于使用“try and catch"时的无限循环“while循环"内的块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆