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

标签 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);
        }

    }

}

最佳答案

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

output 数组的元素最初全部为 null。当你稍后说

output[i] += fileLine;

这会导致 fileLine附加null,从而导致 null 引用转换为字符串“null”,然后与 fileLine 的串联。您可以在最小的示例中看到它的工作原理

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

修复方法是使用

output[i] = fileLine;  // = instead of +=

关于java - 读取文本文件 - 在每一行的开头返回 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29123623/

相关文章:

java - 使用 Gson 将指数值转换为 BigDecimal 或 Long

java - 在上一个线程完成工作之前启动下一个线程

c - fscanf() fclose() 或读取文件退出并结束程序

python - 如何仅在特定字符串之后读取文本文件中的行?

css - 如何自动为特定文本实例着色?

java - 如何修复 CWE-470 : Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection' )

java - this.processFtpRequest

java - 使用intent.action.VIEW打开文件时如何获取文件URI?

javascript - 哪些文本可以复制但不能搜索?

javascript - 我应该使用哪种方法从文本中提取指定的数据?