gpt4 book ai didi

java - 文件中的矩阵

转载 作者:行者123 更新时间:2023-12-02 07:50:48 24 4
gpt4 key购买 nike

我正在尝试从文本文件创建矩阵。问题是,当缓冲读取器函数 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

最佳答案

有两件事明显错误:

  • 您不需要变量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]);
}

关于java - 文件中的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10255814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com