无法弄清楚如何捕获InputMismatchException [英] Cannot Figure out how to catch InputMismatchException
本文介绍了无法弄清楚如何捕获InputMismatchException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以这是我当前用于捕获InputMismatchException错误的代码
So here is my current code for catching an InputMismatchException error
int weapon = 0
boolean selection = true;
while(selection) {
try {
System.out.println("Pick number 1, 2, or 3.");
weapon = scan.nextInt();
selection = false;
} catch(InputMismatchException e) {
System.out.println("Choose 1,2,3");
weapon = scan.nextInt();
}
}
我正在努力确保int是输入而不是其他任何东西。
扫描仪课程已经实施,扫描将对我有效。
I'm trying to make sure that an int is entered and not anything else. Scanner class as already been implemented and 'scan' will act as it for me.
感谢您的帮助!
推荐答案
试试这个:
int weapon = 0;
do{
System.out.println("Pick number 1, 2, or 3.");
if(scan.hasNextInt()){
weapon = scan.nextInt();
break;
}else{
System.out.println("Enter an integer only");
scan.nextLine();
}
}while(true);
这将确保它是一个整数,它会一直询问直到它得到它。
This will make sure it is an integer and it will keep asking until it gets it.
这篇关于无法弄清楚如何捕获InputMismatchException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文