2011-11-12 40 views
1

得到正確的布爾輸出我寫了一個布爾方法,可以調用它從文件中讀取信息。如果拋出某些異常,該方法應該返回布爾值「false」。如果不是,它應該返回值「真」。但是,無論如何,該方法始終返回值「true」。正在讀取的實際文件在第一行中有一個數字(代表星期編號),其餘行包含每行一個患者的治療信息。我的代碼如下:無法從方法(Java)

public boolean readTreatmentsFromFile(String filename) { 
    boolean value = true; 
    try { 
    FileReader textFileReader = new FileReader(filename); 
    BufferedReader textReader = new BufferedReader(textFileReader); 

    System.out.println("READING TREATMENTS FROM FILE: " + filename); 

    int week = Integer.parseInt(textReader.readLine()); 

    if (week != weekNumber) { 
     throw new ArithmeticException(); 
    } 

    String post = textReader.readLine(); 

    while(post != null) { 
     addPost(post); 
     if (!addPost(post)) 
     value = false; 
     post = textReader.readLine(); 
    } 
    textReader.close(); 
    } 
    catch (ArithmeticException exception) { 
    System.out.println("Invalid week number in the file: " + filename); 
    value = false; 
    } 
    catch (FileNotFoundException exception) { 
    System.out.print("The file cannot be located"); 
    value = false; 
    } 
    catch (IOException exception) { 
    System.out.print("Cannot read the file:" + filename); 
    value = false; 
    } 

    return value; 
} 

,以我應該如何改變,以它的代碼給我一個正確的布爾結果的任何信息,將不勝感激!

+0

是否有任何異常被拋出? –

+0

實際上,現在我看着輸出,我看到拋出的異常實際上來自addPost方法,我在while循環中使用該方法。讓我仔細看看我的代碼,看看我能否弄清楚。 – Kristian

+0

嗨。我現在試圖說明這樣一個事實,即方法addPost(這是一種將帖子添加到數組,並且返回一個布爾值的方法)也可能引發異常。現在,我得到正確的布爾輸出。但是,由於某種原因,程序打印出與此方法關聯的異常消息兩次。任何想法可能會導致這種情況? – Kristian

回答

3

我會考慮這個:返回一個變量'result',默認爲false;只有成功時纔將其設置爲true。見下面(注意我沒有調試過你的代碼本身):

public boolean readTreatmentsFromFile(String filename) { 
    boolean result = false; // pessimistic default 

     try { 
      FileReader textFileReader = new FileReader(filename); 
      BufferedReader textReader = new BufferedReader(textFileReader); 

      System.out.println("READING TREATMENTS FROM FILE: " + filename); 

      int week = Integer.parseInt(textReader.readLine()); 

      if (week != weekNumber) { 
       throw new ArithmeticException(); 
      } 

      String post = textReader.readLine(); 

      while(post != null) { 
       addPost(post); 
       post = textReader.readLine(); 
      } 
      textReader.close(); 
      result = true; // SUCCESS! 
     } 
     catch (ArithmeticException exception) { 
      System.out.println("Invalid week number in the file: " + filename); 
     } 
     catch (FileNotFoundException exception) { 
      System.out.print("The file cannot be located"); 
     } 
     catch (IOException exception) { 
      System.out.print("Cannot read the file:" + filename); 
     } 

     return result; 
    } 
+0

非常感謝!這使代碼有點「更清潔」:) – Kristian