2013-05-31 36 views
-2

在下面的代碼中,我要求用戶給一個整數輸入,如果輸入是0或負數,它會再次循環,直到給出正數。問題是,如果用戶按下一個字母,我的代碼會崩潰,儘管事實上我在很多方面使用了try-catch,但沒有任何真正的工作。有任何想法嗎? 我在循環內使用了try-catch,但它只適用於一個字母輸入並且不正確。Try-Catch內循環

System.out.print("Enter the number of people: "); 

numberOfPeople = input.nextInt(); 

while (numberOfPeople <= 0) { 

     System.out.print("Wrong input! Enter the number of people again: "); 

     numberOfPeople = input.nextInt(); 

} 

回答

4

在當前的代碼的問題是,你總是試圖接收非整數輸入你不能處理錯誤以正確的方式時,讀取int左右。修改此以始終讀取String並將其轉換爲int

int numberOfPeople = 0; 
while (numberOfPeople <= 0) { 
    try { 
     System.out.print("Enter the number of people: "); 
     numberOfPeople = Integer.parseInt(input.nextLine()); 
    } catch (Exception e) { 
     System.out.print("Wrong input!"); 
     numberOfPeople = 0; 
    } 
} 
//continue with your life...