2014-12-04 107 views
0

首先,這是我的一個班級作業。我理解我的教授試圖解釋的這個任務的所有概念,但我對它持續循環有一個愚蠢的問題,並且無法弄清楚如何阻止它。Java InputMismatchException循環掃描器

我們被要求創建我們自己的Exception類,並在創建時間(包括小時,分鐘和秒)對象時使用將它們拋出到特定實例。但是,我對自己的異常類沒有問題,因爲InputMismatchException不斷被執行,所以我遇到了問題。

這個類通過掃描儀對象讀取一個文件,該對象在每行上包含三個整數以代表軍事格式的時間(例如20 15 33)是8:15:33 P.M.但是一旦出現無效標記(例如二十15 33,其中二十不是整數),它就不會停止InputMismatchException catch塊。

這是代碼:

public class TimeTestNew 
{ 

public static void main (String[] args)throws IllegalHourException, 
     IllegalMinuteException, 
     IllegalSecondException, 
     FileNotFoundException, 
     NumberFormatException 
{ 
    boolean fileFound = false; 

    while(!fileFound) 
    { 
     String input = JOptionPane.showInputDialog("Enter filename: "); 

     try 
     { 
      Scanner in = new Scanner(new File(input)); 
      fileFound = true; 

      while(in.hasNextLine()) 
      { 
       int hour = 0, minute = 0, second = 0; 
       try 
       { 
        hour = in.nextInt(); 
        minute = in.nextInt(); 
        second = in.nextInt(); 
        Time theTime = new Time(hour,minute,second); 
        System.out.println(theTime); 
       } 
       catch(IllegalHourException e) 
       { 
        System.err.println("Sorry, \"" + e.value 
          + "\" is an invalid hour."); 
       } 
       catch(IllegalMinuteException e) 
       { 
        System.err.println("Sorry, \"" + e.value 
          + "\" is an invalid minute."); 
       } 
       catch(IllegalSecondException e) 
       { 
        System.err.println("Sorry, \"" + e.value 
          + "\" is an invalid second."); 
       } 
       catch(NumberFormatException | InputMismatchException e) 
       { 
        System.err.println("Incorrect format used."); 
        // this is what keeps getting executed 

       } 

      } 

      in.close(); 

     } 
     catch (FileNotFoundException e) 
     { 
      System.err.println("ERROR: \"" + input + "\" not found\n" 
        + "Please enter a valid filename."); 
     } 
    } 
} 
} 

這是輸出示例:

12:12:12 P.M. 
Sorry, "24" is an invalid hour. 
1:02:03 A.M. 
1:13:13 P.M. 
Sorry, "90" is an invalid minute. 
Incorrect format used. 
Incorrect format used. 
Incorrect format used. 
Incorrect format used. 
Incorrect format used. 
Incorrect format used. 
Incorrect format used. 
Incorrect format used. 
Incorrect format used. 
Incorrect format used. 
Incorrect format used. 
//...and this goes on forever 

正如你所看到的,它會循環,「使用的格式不正確」的catch塊在裏面的InputMismatchException時一遍又一遍......我無法想出一種方法讓它停止並繼續閱讀文件。

任何幫助將不勝感激解釋一個解決方案,謝謝!

回答

1

問題是while循環的條件不在輸入是否有效,而是如果文件中存在下一行。如果您無法在while循環之前驗證輸入,則應檢查break語句。

+0

我明白你在說什麼。糾正我,如果我誤解你的意思,但我已經嘗試在捕捉IllegalMismatchException之後放置一箇中斷,以便它停止,但是然後程序退出並不再讀取文件的其餘部分,如果存在則會出現問題更多的行被讀取。 – mugiwaragirl 2014-12-04 15:38:23

+0

您是否在捕捉托架內部或外部放置了休息區? – MiiinimalLogic 2014-12-04 15:41:49

+0

在收集括號中,在System.err.println(「使用的格式不正確」); – mugiwaragirl 2014-12-04 15:49:51