我的阵列在哪里改变?
Where does my array change?
这似乎是一个非常微不足道的问题,但我正在尝试将 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 是 class
的 属性 可能也会有所帮助
请原谅我的笨拙。
谢谢!
while (null != (temp = reader.readLine())) {
bools[i] = Boolean.parseBoolean(temp);
// output what you read
System.out.println(bools[i]);
i++;
}
您将所有内容都放在同一个位置。增加您的迭代器变量,它将起作用。
您没有更新 i
值。第一次你得到正确的,因为你的打印值直接来自文件。
这似乎是一个非常微不足道的问题,但我正在尝试将 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 是 class
的 属性 可能也会有所帮助请原谅我的笨拙。 谢谢!
while (null != (temp = reader.readLine())) {
bools[i] = Boolean.parseBoolean(temp);
// output what you read
System.out.println(bools[i]);
i++;
}
您将所有内容都放在同一个位置。增加您的迭代器变量,它将起作用。
您没有更新 i
值。第一次你得到正确的,因为你的打印值直接来自文件。