首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java InputMismatchException

Java InputMismatchException
EN

Stack Overflow用户
提问于 2013-05-29 22:12:33
回答 5查看 74K关注 0票数 7

我有这段代码,我想捕获字母异常,但它总是出现以下错误:

代码语言:javascript
复制
Exception in thread "main" java.util.InputMismatchException
    at java.util.Scanner.throwFor(Scanner.java:840)
    at java.util.Scanner.next(Scanner.java:1461)
    at java.util.Scanner.nextInt(Scanner.java:2091)
    at java.util.Scanner.nextInt(Scanner.java:2050)
    at exercise_one.Exercise.main(Exercise.java:17)

下面是我的代码:

代码语言:javascript
复制
 System.out.print("Enter the number of students: ");

 students = input.nextInt(); 

 while (students <= 0) {

     try {

        System.out.print("Enter the number of students: ");

        students = input.nextInt();

     }

     catch (InputMismatchException e) {

        System.out.print("Enter the number of students");

     }
 }    
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2013-05-29 22:27:49

您可以使用do-while循环来消除第一个input.nextInt()

代码语言:javascript
复制
do {
    try {
        System.out.print("Enter the number of students: ");
        students = input.nextInt();
    } catch (InputMismatchException e) {
        System.out.print("Invalid number of students. ");
    }
    input.nextLine(); // clears the buffer
} while (students <= 0);
票数 10
EN

Stack Overflow用户

发布于 2013-05-29 22:14:31

doc

Scanner.nextInt将输入的下一个标记扫描为整数。如果下一个标记与整数正则表达式不匹配或超出范围

因此,您似乎没有输入任何整数作为输入。

您可以使用

代码语言:javascript
复制
     while (students <= 0) {

         try {
            System.out.print("Enter the number of students: ");

            students = input1.nextInt();

         }

         catch (InputMismatchException e) {
             input1.nextLine();
         }
     } 
票数 3
EN

Stack Overflow用户

发布于 2020-04-12 22:37:52

从扫描仪读取数据并将其分配给Int类型。由于您提供的是字符串,这将抛出异常。要处理这种情况,必须只在Try- Catch块中编写代码片段。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16816250

复制
相关文章

相似问题

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