我编写的代码
1)不断要求用户选择数字并检查输入是否为整数
private static int readInputInt(String error) {
Scanner s = new Scanner(System.in);
while (!s.hasNextInt()) {
System.out.println(error);
s.next();
}
int result = s.nextInt();
//s.close();
return result;
}
2)不断要求用户选择范围内的数字并仅显示错误,程序不显示要求用户再次提供输入的消息。
private static int readInputInt(String error, int max) {
Scanner s = new Scanner(System.in);
int result;
do {
while(!s.hasNextInt()) {
//show error if it is not integer and get input once again
System.out.println(error);
s.next();
}
result = s.nextInt();
// if result is integer check if it is bigger than max
if(result > max) {
System.out.println(error);
}
}while(result > max);
我想知道是否有更简单的方法可以做到这一点,因为我花了太多时间来做这件事,我认为这是垃圾编码方式。
首先,我认为下面的代码会起作用:
private static int readInputInt(String error, int max) {
Scanner s = new Scanner(System.in);
while (!s.hasNextInt() && (s.nextInt < max)) {
System.out.println(error);
s.next();
}
int result = s.nextInt();
//s.close();
return result;
}
但它不起作用。如有任何帮助,谢谢!
答案 0 :(得分:1)
我在编写代码时多次遇到此问题,通常最适合我的解决方案是使用
尝试/捕捉
让我告诉你我的意思。
private static int readInputInt(String error) {
Scanner s = new Scanner(System.in);
//1. Reading the input as a string.
String input = s.nextLine();
int result;
// A while loop that will keep going on until the user enters a
// valid integer.
while (true) {
// Try/catch block that tries to parse the string to an integer
try {
// If the user enters a valid integer there will be no problem
// parsing it. Otherwise, the program will throw a 'NumberFormatException'.
result = Integer.parseInt(input);
// If the parsing has been successful,
//we break the while loop and return the result
break;
}catch(NumberFormatException nfe) {
// If the user did not enter a valid integer we will just
// print the error message.
System.out.println(error);
}
// Read user input again and repeat the procedure above.
input = s.nextLine();
}
return result;
}
我希望这有帮助。如果您不熟悉尝试/捕获,我建议您在线阅读。它整洁!
答案 1 :(得分:1)
private static int readInputInt(String error, int max) {
Scanner s = new Scanner(System.in);
int result;
while (true) {
if (s.hasNextInt()) {
result = s.nextInt();
if (result <= max) {
s.close();
return result;
}
} else { //Only want to call next() if it doesn't meet the first conditional. We've already called next when it is an int.
s.next();
}
System.out.println(error);
}