在While循环中尝试捕捉

 mobiledu2502910157 发布于 2023-01-01 23:02

下面的代码询问用户他/她想要多少赛车手.

while (true) { // loops forever until break
    try { // checks code for exceptions
        System.out.println("How many racers should" + " participate in the race?");
        amountRacers = in.nextInt();
        break; // if no exceptions breaks out of loop
    } 
    catch (InputMismatchException e) { // if an exception appears prints message below
        System.err.println("Please enter a number! " + e.getMessage());
        continue; // continues to loop if exception is found
    }
}

如果在amoutnRacers = in.nextInt();代码中输入一个数字,则循环出来并且程序的其余部分运行正常; 但是,当我输入诸如"awredsf"之类的内容时,它应该捕获该异常,它会这样做.而不是再次提示用户它不断循环,这对我来说没有意义.

程序在连续循环时打印如下:

有多少参赛者应参加比赛?有多少参赛者应参加比赛?有多少参赛者应参加比赛?有多少参赛者应参加比赛?有多少参赛者应参加比赛?有多少参赛者应参加比赛?有多少赛车手参加比赛?请输入一个号码!null请输入一个数字!null请输入一个数字!null请输入一个数字!null请输入一个数字!null请输入一个数字!null请输入一个数字!空值 ...

我不明白发生了什么amountRacers = in.nextInt();,为什么用户无法输入号码?

1 个回答
  • input.next()一旦捕获InputMismatchException,只需添加 .

    catch (InputMismatchException e) { //if an exception appears prints message below
        System.err.println("Please enter a number! " + e.getMessage());
        input.next(); // clear scanner wrong input
        continue; // continues to loop if exception is found
    }
    

    您需要清除错误的输入,而扫描仪自动不会.

    2023-01-01 23:22 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有