所以我写了几个方法,要求用户输入他们想要的时间(1-24)。然而,我需要检查它们是否输入 int 以及 1-24 之间的数字。问题是,如果发送到错误语句,扫描仪会被多次调用。我不知道如何在没有这些问题的情况下做到这一点。
public static int getHour(Scanner scan){
int hour=0;
System.out.println("Enter the hour for the showtime (1-24):");
do{
if((!scan.hasNextInt())||((hour=scan.nextInt())<1)||(hour>24)){
System.out.println("Enter a valid number");
scan.next();
} else{
return hour;
}
}while((!scan.hasNextInt())||(hour<1)||(hour>24));
return hour;
}
理想情况下,它仅在输入无效输入(例如 1-24 之外的字符串或整数)时提示一次。但它会提示两次,有时甚至一次,具体取决于您输入错误输入的顺序。
如有任何帮助,我们将不胜感激,谢谢
最佳答案
您遇到此问题是因为 .hasNextInt()
不会前进超过输入,而 .nextInt()
仅在翻译成功时前进。因此,循环和 if 语句的组合可能会导致扫描仪是否前进的困惑。下面是重写的方法,让扫描仪对每个错误输入仅提示一次:
public int getHour(Scanner scan) {
System.out.printf("%nEnter the hour for the showtime (1-24): ");
while (true) {
input = scan.next();
entry = -1;
try {
entry = (int)Double.parseDouble(input);
} catch (NumberFormatException e) {
// Ensures error is printed for all bad inputs
}
if (entry >= 1 && entry <= 24) {
return entry;
}
System.out.printf("%nEnter a valid number: ");
}
}
在这种情况下,我更喜欢使用无限循环,但由于这可能很危险,因此请谨慎接收。希望这有帮助!
关于java - 如何使用扫描仪检查用户输入而不多次提示扫描仪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55893323/