我是编程新手,我目前正在学习Java课程,我必须验证用户的扫描仪输入。下面的代码似乎有效,但我认为它有点效率低下。必须有更好的方法来做到这一点!
欢迎您的建议!
以下是我所拥有的:
do {
System.out.println("What is you age?");
while (!scSudoku.hasNextInt()) {
System.out.println("You must enter an number");
scSudoku.next();
}
age = scSudoku.nextInt();
if (age < 10 || age > 90) {
System.out.println("You age must be within 10 and 90");
}
} while (age < 10 || age > 90);
答案 0 :(得分:1)
使用nextLine()
丢弃任何错误输入。
使用永不停止的循环防止代码重复,并break
或return
退出循环。我更喜欢在辅助方法中隔离代码并使用return
。
private static int promptAge(Scanner sc) {
System.out.println("What is you age?");
for (;;) {
if (! sc.hasNextInt()) {
System.out.println("You must enter an number");
} else {
int age = sc.nextInt();
if (age >= 10 && age <= 90)
return age;
System.out.println("You age must be within 10 and 90");
}
sc.nextLine(); // discard (rest of) line of input
}
}
答案 1 :(得分:0)
尝试将scSudoku.next();
替换为scSudoku.nextLine
。它可能运行得更顺畅,但我的Java有点生疏。
我记得使用nextLine
或nextln
代替next
而不是scSudoku.next();
,而且程序也有效。
编辑:
尝试将scSudoku.nextln
替换为nextln
。似乎nextWhateverYou'reUsing
被更广泛地使用。
编辑2:
或者只使用(defun string-or-function-p (x)
(typep x '(or string function)))
。