读取文本文件 - 在每行的开头返回null?

时间:2015-03-18 13:38:51

标签: java file text

感谢您抽出宝贵时间阅读本文。我正在创建一个程序,向用户打印每日报价。整个程序运行正常,但是当我向用户打印引号时,他们会这样读: null真相抵制简单。文本文档中的这些引号之前没有空格。我有一种感觉这与初始化变量有关,但我不确定哪一个,或者最好如何初始化它。谢谢你的时间。

static String[] output = new String[12];
    static String file = "";
    static int counter = 0;

    public static void main(String[] args) throws IOException {
        BufferedReader fileRead = new BufferedReader(new FileReader("C:\\Users\\Owner\\Documents\\quotes.txt"));
        String fileLine = "";
        for (int i = 0; i < 12; i++) {
            fileLine = fileRead.readLine();
            if (fileLine == null) {
                break;
            }
            output[i] += fileLine;
            output[i] += "\n";
        }
        JOptionPane.showMessageDialog(null, output[counter]);
        counter++;
        fileRead.close();
        int ans = JOptionPane.showConfirmDialog(null, "Want to see another quote?", "Daily Quote", JOptionPane.YES_NO_OPTION);
        if (ans == JOptionPane.YES_OPTION) {
            do {
                JOptionPane.showMessageDialog(null, output[counter]);
                counter++;
                ans = JOptionPane.showConfirmDialog(null, "Want to see another quote?", "Daily Quote", JOptionPane.YES_NO_OPTION);
            } while (ans == JOptionPane.YES_OPTION);
            JOptionPane.showMessageDialog(null, "Thanks for using the Daily Quotation machine! Have a nice day!",
                    "Daily Quote", JOptionPane.INFORMATION_MESSAGE);
        }

    }

}

1 个答案:

答案 0 :(得分:2)

使用

static String[] output = new String[12];

output数组的元素原来都是null。当你后来说

output[i] += fileLine;

这会导致fileLine 追加null,从而导致将空引用转换为字符串“null”,然后将{{1}连接起来}}。您可以在最小示例中看到这一点

fileLine

修复是使用

class Foo {
  public static void main(String args[]) {
    String s = null;
    s += "foo";
    System.out.println(s);  // prints "nullfoo"
  }
}