美文网首页
关于try、catch在while中会产生无限循环的问题

关于try、catch在while中会产生无限循环的问题

作者: 虚无一代 | 来源:发表于2018-06-14 21:49 被阅读0次
int choice = 0;
            boolean isRight = true;
            while (isRight){
                try {
                    isRight = false;
                    choice = input.nextInt();
                }
                catch (InputMismatchException ex){
                    System.out.println("Please enter just one number!");
                    isRight = true;
                }
            }

想检测用户的输入是否是整数,如果不是就让他再输。一开始报错了,代码如上。后改正,代码如下:

int choice = 0;
            boolean isRight = true;
            while (isRight){
                try {
                    Scanner input1 = new Scanner(System.in);
                    isRight = false;
                    choice = input1.nextInt();
                }
                catch (InputMismatchException ex){
                    System.out.println("Please enter just one number!");
                    isRight = true;
                }
            }

原来需要重新Scanner一下,否则之前的的输入一直残留在其中,就会一直报错。

相关文章

网友评论

      本文标题:关于try、catch在while中会产生无限循环的问题

      本文链接:https://www.haomeiwen.com/subject/wvyueftx.html