从文件中读取一列整数值后得到零
Getting zero after reading a column of integer values from a file
所以我已经被这个问题困扰了一个星期了。
我需要从我正在阅读的文件的最后一列中获取值。
但是当我尝试在 while 循环之外读取该数组时,我得到的是零而不是值。
但是如果我在 while 循环中读取同一个数组,我会得到非常好的值。
BufferedReader br2 = new BufferedReader(new FileReader("/home/manofsteel/yeast_training.txt"));
// Starting to read a file line by line.
while((line = br2.readLine()) != null)
{
row = 0;
String[] valsNew = line.trim().split("\s+"); /* Getting rid of all
spaces since the file
contains a lot of them. */
cla = new int[lines];
cla[row] = Integer.parseInt(valsNew[8]); /* 8 because i need the
values from last column. */
row++;
}
for(int i=0;i<cla.length;i++)
{
// Trying to print back that array.
System.out.println("x"+cla[i]);
}
}
我得到的输出是
x0
x0
x0
x0
我想要的输出是
x4
x1
x1
x1
x2
x7
x2
x7
欢迎提出任何建议。
如果您认为我需要共享输入文件。请告诉我。
谢谢。
我认为这永远行不通,因为您用来存储数据的数组在每次迭代中总是 re-initialized:
cla = new int[lines];
而且,我不确定您是否总是希望在每次执行新迭代时都将行设置为零(因为最后您正在执行行++;):
row = 0;
所以我已经被这个问题困扰了一个星期了。
我需要从我正在阅读的文件的最后一列中获取值。 但是当我尝试在 while 循环之外读取该数组时,我得到的是零而不是值。
但是如果我在 while 循环中读取同一个数组,我会得到非常好的值。
BufferedReader br2 = new BufferedReader(new FileReader("/home/manofsteel/yeast_training.txt"));
// Starting to read a file line by line.
while((line = br2.readLine()) != null)
{
row = 0;
String[] valsNew = line.trim().split("\s+"); /* Getting rid of all
spaces since the file
contains a lot of them. */
cla = new int[lines];
cla[row] = Integer.parseInt(valsNew[8]); /* 8 because i need the
values from last column. */
row++;
}
for(int i=0;i<cla.length;i++)
{
// Trying to print back that array.
System.out.println("x"+cla[i]);
}
}
我得到的输出是
x0
x0
x0
x0
我想要的输出是
x4
x1
x1
x1
x2
x7
x2
x7
欢迎提出任何建议。
如果您认为我需要共享输入文件。请告诉我。
谢谢。
我认为这永远行不通,因为您用来存储数据的数组在每次迭代中总是 re-initialized:
cla = new int[lines];
而且,我不确定您是否总是希望在每次执行新迭代时都将行设置为零(因为最后您正在执行行++;):
row = 0;