gpt4 book ai didi

java - 读取文件,将字符串转换为 double ,存储在二维数组中

转载 作者:太空宇宙 更新时间:2023-11-04 08:42:55 27 4
gpt4 key购买 nike

我需要读取文件中的数字列表并将其存储到二维数组中。这是我到目前为止所拥有的。我将如何实现这个目标?

//this is only part of my code
public class RainFall
{

double[][] precip;

public RainFall()
{
precip = new double [5][12];
}

public void readFile(BufferedReader infile) throws IOException
{
FileInputStream infile = new FileInputStream("numbers.dat");
BufferedReader br = new BufferedReader(new InputStreamReader(infile));

String[][] myarray = new String[5][12];
while (infile.readLine() != null)
{
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 12; i++)
{
myarray[j][i] = infile.readLine();
}

}


}
infile.close();
}

numbers.dat 是 60 行:

1.01
0.03
2.14
0.47

最佳答案

//Is each number on a new line? You're very close, I added a few lines below. 

public class RainFall

{

double[][] precip;

public RainFall()
{
precip = new double [5][12];
}

public void readFile(BufferedReader infile) throws IOException
{
//FileInputStream infile = new FileInputStream("numbers.dat");
BufferedReader br = new BufferedReader(new FileReader("numbers.dat"));
String line = "";
String[][] myarray = new String[5][12];

while ((line = br.readLine()) != null)
{
double num = Double.parseDouble(line.trim());
for (int j = 0; j < 5; j++)
{
for (int i = 0; i < 12; i++)
{
precip[j][i] = num;
}

}


}
br.close();
}

关于java - 读取文件,将字符串转换为 double ,存储在二维数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4940854/

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