这似乎是一个非常微不足道的问题,但我正在尝试将一个 boolean 值数组写入文件,然后将它们读回到数组中。我可以验证文件是否已正确创建:
true
false
true
false
false
false
但是当我尝试读回它时,我最终得到一个完全充满 false 的数组。这是我的阅读代码:
bools = new boolean[bools.length];
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String temp;
int i = 0;
while (null != (temp = reader.readLine())) {
bools[i] = Boolean.parseBoolean(temp);
// output what you read
if (bools[i]) {
System.out.println("true!");
} else {
System.out.println("false!");
}
}
reader.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(BooleanFiles.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(BooleanFiles.class.getName()).log(Level.SEVERE, null, ex);
}
// now output the resulting array
for (int i = 0; i < bools.length; i++) {
if (bools[i]) {
System.out.println("true!");
} else {
System.out.println("false!");
}
}
这是我得到的输出:
true!
false!
true!
false!
false!
false!
false!
false!
false!
false!
false!
false!
让我发疯的部分是,当我在阅读时(在 while 循环中)检查数组时,数组设置正确,但当我在最后(在 for 循环中)检查数组时,它是错误的。
了解 bools 是类的属性也可能会有所帮助
请原谅我的无知。 谢谢!
最佳答案
while (null != (temp = reader.readLine())) {
bools[i] = Boolean.parseBoolean(temp);
// output what you read
System.out.println(bools[i]);
i++;
}
您将所有内容都放在同一个位置。增加你的迭代器变量,它就会起作用。
关于java - 我的数组在哪里发生了变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29953751/