Java InputMismatchException [英] Java InputMismatchException

查看:240
本文介绍了Java InputMismatchException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 线程中的异常

我有这个代码,我想抓住信件异常,主要java.util.InputMismatchException
在java.util.Scanner.throwFor(Scanner.java:840)
在java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
在java.util.Scanner.nextInt(Scanner.java:2050)
在exercise_one.Exercise.main(Exercise.java:17)

这里是我的代码:

  System.out.print(输入学生人数); 

students = input.nextInt();

while(students< = 0){

try {

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

students = input.nextInt();

}

catch(InputMismatchException e){

System.out.print(输入学生人数);

}
}


解决方案

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

  do {
try {
System.out.print(输入学生人数);
students = input.nextInt();
} catch(InputMismatchException e){
System.out.print(学生数量无效);
}
input.nextLine(); //清除缓冲区
} while(students< = 0);

因此,所有 InputMismatchException 可以在一个地方。


I have this code and I want to catch the letter exception but it keeps having these errors:

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)

And here is my code:

 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");

     }
 }    

解决方案

You can use a do-while loop instead to eliminate the first input.nextInt().

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);

Therefore all InputMismatchException can be handled in one place.

这篇关于Java InputMismatchException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆