我正在使用java中的掃描儀,并且僅在檢測到用戶選擇的整數時才嘗試讓程序繼續,但我編寫的代碼沒有提供該功能。這是我的代碼:import java.util.Scanner;/** * * @author Ansel */public class Test { public static void main(String[] args) { Scanner scan = new Scanner (System.in); AddressBook ad1 = new AddressBook(); String firstName=""; String lastName=""; String key=""; String street=""; String city=""; String county=""; String postalCode=""; String mNumber=""; int choice=0; do{ System.out.println("********************************************************************************"); System.out.println("Welcome to the Address book. Please pick from the options below.\n"); System.out.println("1.Add user \n2.Remove user \n3.Edit user \n4.List Contact \n5.Sort contacts \n6.Exit"); System.out.print("Please enter a choice: "); int reloop = 0; do { try { scan.nextLine(); choice = scan.nextInt(); reloop ++; } catch (Exception e) { System.out.println ("Please enter a number!"); }} while(reloop == 0); if(choice==1){ //Add user System.out.print("Please enter firstname: "); firstName=scan.next(); System.out.print("Please enter lastname: "); lastName=scan.next(); scan.nextLine(); System.out.print("Please enter street:"); street=scan.nextLine(); System.out.print("Please enter city: "); city=scan.next(); System.out.print("Please enter county: ");此代碼在運行時要求輸入一個數字。例如,如果您輸入一個字母,它會顯示一個空行,直到您輸入另一個字母,然后它會說請輸入一個數字。我不明白為什么它沒有說,一旦出現字母或除整數之外的任何內容,請輸入數字
1 回答

泛舟湖上清波郎朗
TA貢獻1818條經驗 獲得超3個贊
只需使用Scanner.nextLine和Integer.parseInt即可避免混亂。
Scanner scan = new Scanner(System.in);
int choice = 0;
System.out.print("Please enter a choice: ");
int reloop = 0;
do {
try {
String input = scan.nextLine(); // Scan the next line from System.in
choice = Integer.parseInt(input); // Try to parse it as an int
reloop++;
} catch (Exception e) {
System.out.println("Please enter a number!");
}
} while (reloop == 0);
您也可以使用nextLineafter everynextInt來終止該行,但我更喜歡單獨解析int,如上所述。它更清晰、更詳細。
添加回答
舉報
0/150
提交
取消