首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何修复InputMismatchException

如何修复InputMismatchException
EN

Stack Overflow用户
提问于 2012-04-08 07:15:56
回答 1查看 4.9K关注 0票数 1

所以我有这样的代码:

代码语言:javascript
复制
protected void giveNr(Scanner sc) {
    //variable to keep the input
    int input = 0;
    do {
      System.out.println("Please give a number between: " + MIN + " and " + MAX);
      //get the input
      input = sc.nextInt();
    } while(input < MIN || input > MAX);
}

如果输入的内容不是整数,比如字母或字符串,程序就会崩溃,并给出错误InputMismatchException。我如何修复它,以便当输入了错误的输入类型时,再次要求人类输入(并且程序不会崩溃?)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-04-08 07:43:12

您可以捕获InputMismatchException,打印一条错误消息,告诉用户哪里出了问题,然后再次循环:

代码语言:javascript
复制
int input = 0;
do {
    System.out.println("Please give a number between: " + MIN + " and " + MAX);
    try {
        input = sc.nextInt();
    }
    catch (InputMismatchException e) {
        System.out.println("That was not a number.  Please try again.");
        input = MIN - 1; // guarantee we go around the loop again
    }
while (input < MIN || input > MAX)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10059143

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档