我正在使用java中的掃描儀,并且僅在檢測(cè)到用戶選擇的整數(shù)時(shí)才嘗試讓程序繼續(xù),但我編寫(xiě)的代碼沒(méi)有提供該功能。這是我的代碼: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: ");此代碼在運(yùn)行時(shí)要求輸入一個(gè)數(shù)字。例如,如果您輸入一個(gè)字母,它會(huì)顯示一個(gè)空行,直到您輸入另一個(gè)字母,然后它會(huì)說(shuō)請(qǐng)輸入一個(gè)數(shù)字。我不明白為什么它沒(méi)有說(shuō),一旦出現(xiàn)字母或除整數(shù)之外的任何內(nèi)容,請(qǐng)輸入數(shù)字
1 回答

泛舟湖上清波郎朗
TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超3個(gè)贊
只需使用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來(lái)終止該行,但我更喜歡單獨(dú)解析int,如上所述。它更清晰、更詳細(xì)。
添加回答
舉報(bào)
0/150
提交
取消