如何循环用户输入直到输入整数? [英] How to loop user input until an integer is inputted?
本文介绍了如何循环用户输入直到输入整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 Java 新手,我想继续要求用户输入,直到用户输入一个整数,这样就不会出现 InputMismatchException.我已经尝试过这段代码,但是当我输入一个非整数值时仍然出现异常.
I'm new to Java and I wanted to keep on asking for user input until the user enters an integer, so that there's no InputMismatchException. I've tried this code, but I still get the exception when I enter a non-integer value.
int getInt(String prompt){
System.out.print(prompt);
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()){
System.out.println("Enter a whole number.");
sc.nextInt();
}
return sc.nextInt();
}
感谢您的时间!
推荐答案
在处理 Juned 的代码时,我能够缩短它.
Working on Juned's code, I was able to make it shorter.
int getInt(String prompt) {
System.out.print(prompt);
while(true){
try {
return Integer.parseInt(new Scanner(System.in).next());
} catch(NumberFormatException ne) {
System.out.print("That's not a whole number.
"+prompt);
}
}
}
这篇关于如何循环用户输入直到输入整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文