所以这是我当前的代码,用于捕获InputMismatchException错误
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,而不要输入其他任何内容。已经实施的扫描仪类,“扫描”将对我起作用。
多谢您的协助!
尝试这个:
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);
这将确保它是一个整数,并且会一直询问直到获得它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句