Redoing a try after catch in Java

删除回忆录丶 提交于 2019-12-06 15:54:52

The documentation for java.util.Scanner states

When a scanner throws an InputMismatchException, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.

So you'll retrieve indefinitely using this method. In the catch block you'll need to skip over the token.

As well as Jeff's answer, there's no indication that anything will ever set condition back to true after it's been set to false once. You could make it a local variable, or you could just return from the try block:

public int intInput(String text)    
{
    do
    {
        System.out.print(text);
        try
        {
            return scanner.nextInt();
        }
        catch (java.util.InputMismatchException error)
        {
            System.out.println("Please use valid input.");
            // Consume input here, appropriately...
        }
    } while (true);
}

Now the method doesn't affect any state other than the scanner, which is probably what you want - and (IMO) it's simpler as well.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!