[英]How to have check user input using scanner without having scanner prompt multiple times
因此,我編寫了一些方法,要求用戶輸入他們想要的時間(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: ");
}
}
在這種情況下,我更喜歡使用無限循環,但是這樣做可能很危險,因此請謹慎使用。 希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.