使用"try and catch"时出现无限循环块在"while循环"内部 [英] Endless loop while using "try and catch " block inside a "while loop"

查看:127
本文介绍了使用"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天全站免登陆