我已经编写了代码
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;
}
但它不起作用。如需任何帮助,谢谢!
最佳答案
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);
}
关于Java 验证用户整数输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49438310/