-1

我正在編寫一個程序,該程序使用Scanner類並希望使用try-catch塊來捕獲InputMismatchExceptions。這就是我寫:如何保持捕獲異常直到它正確java

public class StudentInfo{ 

public static void main(String[] args){ 
    Scanner scnr = new Scanner(System.in); 
    int creditHours = 0; 
    try 
    { 
     System.out.println("Please enter the number of credit hours that you currently have (do not count credit hours from classes that you are currently attending this semester)"); 
     creditHours = scnr.nextInt(); 
    } 
    catch(InputMismatchException e){ 
     System.out.println("CLASSIFICATION ERROR: NUMBER NOT RECOGNIZED. ENTER AN INTEGER FOR CREDIT HOURS"); 
     Scanner input = new Scanner(System.in); 
     creditHours = input.nextInt(); 
    } 
    String studentClass = checkStudent (creditHours); 
    System.out.println("Official Student Classification: " + studentClass); 
    } 

的try-catch塊各地工作一次在,如果我把在24.5例如第一次,它捕獲異常,並在用戶重新輸入數量他們有信用小時,但如果他們第二次重新輸入一個非整數,它不會再次捕獲錯誤併發出相應的消息。所以基本上,我想知道是否有任何方法可以繼續捕捉異常併發出錯誤消息,無論他們嘗試多少次。我試過使用do-while循環或while語句,但它不起作用,所以是的。另外,我在catch塊中創建了一個新的掃描器變量,因爲如果不是這樣,它不允許我在出於某種原因給出錯誤消息之後輸入新的整數。它實際上會拋出我輸入的錯誤,然後繼續給我Java的InputMismatchException錯誤。

這是我在嘗試使用while循環:

int creditHours = 0; 
    while(creditHours <= 0){ 
    try 
    { 
     System.out.println("Please enter the number of credit hours that you currently have (do not count credit hours from classes that you are currently attending this semester)"); 
     creditHours = scnr.nextInt(); 
    } 
    catch(InputMismatchException e){ 
     System.out.println("CLASSIFICATION ERROR: NUMBER NOT RECOGNIZED. ENTER AN INTEGER FOR CREDIT HOURS"); 
     Scanner input = new Scanner(System.in); 
     creditHours = input.nextInt(); 
    } 
    } 

    String studentClass = checkStudent (creditHours); 
    System.out.println("Official Student Classification: " + studentClass); 
    } 
+1

的try/catch不是一個循環。如果你想循環行爲,你必須添加一個循環。例如'while(1){try ... catch ...}' –

+0

@MarcB就像我在我的問題中說過的,我已經做了一段時間和一個do-while循環,但都沒有工作。它完全一樣。 – user2161312

+0

然後顯示你的循環嘗試。 –

回答

0

您需要在try-catch是在一個循環,以重新運行代碼。

試試這個:

public class StudentInfo{ 

public static void main(String[] args){ 

    int creditHours = 0; 
    boolean ok = false; 
    System.out.println("Please enter the number of credit hours that you currently have (do not count credit hours from classes that you are currently attending this semester)"); 

    while (!ok) 
    { 
     try 
     { 
      Scanner scnr = new Scanner(System.in); 
      creditHours = scnr.nextInt(); 
      ok = true; 
     } 
     catch(InputMismatchException e){ 
      System.out.println("CLASSIFICATION ERROR: NUMBER NOT RECOGNIZED. ENTER AN INTEGER FOR CREDIT HOURS"); 
     } 
    } 


    String studentClass = checkStudent (creditHours); 
    System.out.println("Official Student Classification: " + studentClass); 
    } 
+0

非常感謝!它的工作,我完全理解它。非常感謝你! – user2161312