1

我對這段代碼的問題如下:變量號不能是一個字符串,所以我嘗試使用try,catch(InputMissmatchException)語句來處理這個問題。但是,當進入循環並且有人輸入一個字符串時,異常是句柄,但是它會使用最後一個有效條目再次循環。即我輸入5,然後輸入「hello」,結果是:「您必須輸入一個數字。」但是現在5再次被計數。在while循環中的異常處理

這使計數器添加一個太多的計數變量。如果用戶繼續使用字符串,則循環會一直添加最後一個有效條目,因此計數在最後會錯誤。

從邏輯上講,我希望程序處理問題並要求用戶輸入正確的條目,直到輸入可接受的整數,而不再通過while循環;當用戶輸入有效的條目時,保持循環或存在(-1)。

int number = 0; 
int[] count = new int[11]; 

    try 
     { 
     number = input.nextInt(); 
     } 
     catch (InputMismatchException y) 
     { 
     System.out.println("You must enter a number."); 
     input.nextLine(); 

     }  


    while (number != -1) 
    { 
     try 
     { 
      ++count[number]; 
     } 
     catch (IndexOutOfBoundsException e) 
     { 
      System.out.println("Please enter a valid number from the menu."); 
     } 

     try 
     { 
     number = input.nextInt(); 
     } 
     catch (InputMismatchException y) 
     { 
     System.out.println("You must enter a number."); 
     input.nextLine(); 

     } 
    } 

回答

1

聽起來像是你想有一個while循環,直到他們進入一些

int number = 0; 
int[] count = new int[11]; 

while(true) { 
    try 
    { 
    number = input.nextInt(); 
    break; 
    } 
    catch (InputMismatchException y) 
    { 
    System.out.println("You must enter a number."); 
    input.nextLine(); 

    } 
} 


while (number != -1) 
{ 
    try 
    { 
     ++count[number]; 
    } 
    catch (IndexOutOfBoundsException e) 
    { 
     System.out.println("Please enter a valid number from the menu."); 
    } 

    while(true) { 
     try 
     { 
      number = input.nextInt(); 
      break; 
     } 
     catch (InputMismatchException y) 
     { 
      System.out.println("You must enter a number."); 
      input.nextLine(); 
     } 
    } 

}