繁体   English   中英

循环try-catch不起作用

[英]Looping try-catch isn't working

我将如何正确循环此try catch语句? 据我所知, playerIntInput = reader.nextInt(); try块中的代码将被执行,如果存在则捕获异常,这将导致loop = false永远不会到达。 然后,它在catch块中输出消息,并且应该循环回到try并再次请求输入。 相反,我只是从catch块获得了无限循环的输出。

void CheckInput(int playerIntInput) {
    boolean loop = true;

    while(loop=true) {
        try {
            playerIntInput = reader.nextInt();
            loop = false;
        }
        catch(InputMismatchException e) {
            System.out.println("Invalid character was used, try again.");
        }
    }
}

您使用了赋值运算符= ,因此选中时loop始终为true ,而不是==运算符。 您可以使用while(loop == true) ,但是loop已经是一个boolean 最简单的解决方案是while(loop)

另外,如果nextInt存在错误,则不会消耗输入。 catch块中调用next()以使用非数字输入并前进通过它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM