我正在尝试从文本文件创建矩阵。问题是,当缓冲读取器函数readline()完成解析第一行文件时,它会到达第二行,但是它将其读为空,而不是。
void covar()
{
double [][]covar=new double[10][5];
int i=0;
int j=0;
try
{
FileInputStream fstream = new FileInputStream("class 1\\feature_vector.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String input;
while((input=br.readLine())!= null)
{
String [] temp=input.split(",");
//System.out.println(input.split(",").length);
covar[i][j]= new Double(temp[0]);
covar[i+1][j]=new Double(temp[1]);
covar[i+2][j]=new Double(temp[2]);
covar[i+3][j]=new Double(temp[3]);
covar[i+4][j]=new Double(temp[4]);
//i=0;
j++;
}
in.close();
}
catch(Exception e)
{
e.printStackTrace();
}
以上是代码。文件名是完美的,流的东西没有任何问题。你能帮助我解决这个问题吗?
以下是文件的内容:
0.75,321.0,0.22429906,0.97507787,1.966202512778112
0.33333334,135.0,-0.014814815,1.0,5.323770568766052
0.64285713,311.0,0.025723472,1.0,4.764298570227433
0.6,188.0,0.03723404,1.0,4.7349608150168105
0.25,189.0,0.16931216,0.98941797,7.15681209803803
0.71428573,194.0,-0.26804122,0.96391755,5.1654456838422425
0.6,173.0,0.028901733,1.0,6.54275787030257
0.2857143,257.0,0.031128405,1.0,6.095356508899233
0.23076923,197.0,-0.04568528,1.0,3.784908227189768
0.18181819,231.0,0.17316018,0.987013,5.956322938602553
答案 0 :(得分:1)
有两件事显然是错误的:
i
,因为其中一个维度是固定的,并且您将循环“展开”了五次j
应该先行,这是从0
更改为9
的那个。例如:
String [] temp=input.split(",");
covar[j][0] = new Double(temp[0]);
covar[j][1] =new Double(temp[1]);
covar[j][2] =new Double(temp[2]);
covar[j][3] =new Double(temp[3]);
covar[j][4] =new Double(temp[4]);
您可以将循环放回来缩短代码:
String [] temp=input.split(",");
for (int i = 0 ; i != 5 ; i++) {
covar[j][i] = new Double(temp[i]);
}
答案 1 :(得分:1)
看起来你正在为矩阵使用错误的索引,我认为它应该是这样的:
int i = 0;
while((input=br.readLine())!= null) {
String [] temp=input.split(",");
//System.out.println(input.split(",").length);
covar[i][0]= new Double(temp[0]);
covar[i][1]=new Double(temp[1]);
covar[i][2]=new Double(temp[2]);
covar[i][3]=new Double(temp[3]);
covar[i][4]=new Double(temp[4]);
++i;
}
答案 2 :(得分:0)
您的文件可能有一些奇怪的行终结符,这使得读者认为有一个额外的行。
您可以尝试让代码跳过空行:
while((input=br.readLine())!= null) {
if( input.length() > 0 ){
String [] temp=input.split(",");
for (int i = 0 ; i != 5 ; i++) {
covar[j][i] = new Double(temp[i]);
}
}
++j;
}