gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 04:52:11 24 4
gpt4 key购买 nike

感谢您花时间阅读本文。我正在创建一个程序,向用户打印每日报价。整个程序工作正常,但是当我向用户打印报价时,他们读起来像这样: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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com