读取文件,将字符串转换为double,存储在2d数组中

时间:2011-02-09 02:53:34

标签: java string multidimensional-array double

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

//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

2 个答案:

答案 0 :(得分:1)

//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();
    }

答案 1 :(得分:0)

而不是

String[][] myarray = new String[5][12];

使用

double[][] myarray = new double[5][12];

然后将其转入循环:

myarray[j][i] = Double.parseDouble(infile.readLine());