我的数组在哪里变化



这似乎是一个非常琐碎的问题,但我正在尝试将一个boolean的数组写入一个文件,然后将它们读回数组中。我可以验证文件是否正确创建:

true
false
true
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++;
}

你把所有东西都放在同一个位置。增加迭代器变量,它就会工作。

您没有更新i值。第一次正确获取是因为您直接从文件中打印值。

最新更新