无法从方法(Java)获取正确的布尔输出

时间:2011-11-12 23:11:47

标签: java methods boolean readfile

我编写了一个布尔方法,可以调用该方法从文件中读取信息。如果抛出某些异常,则该方法应返回布尔值“false”。如果不是,则应返回值“true”。但是,无论如何,该方法始终返回值“true”。正在读取的实际文件在第一行中具有数字(表示周数),并且其余行包括每行的一个患者的治疗信息。我的代码如下:

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;
}

有关如何更改代码以便为我提供正确的布尔结果的任何信息将非常感谢!

1 个答案:

答案 0 :(得分: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;
    }