如何从文本文件数据中填充2D数组

时间:2014-04-03 12:54:19

标签: java arrays double multidimensional-array

我试图用文本文件中的数据填充二维数组。 这是文本文件:

Newfoundland and Labrador     545.3     540.9     537.9     533.8     531.6
Prince Edward Island          136.9     137.8     138.3     138.9     139.9
Nova Scotia                   936.1     941.2     942.3     942.9     944.8
New Brunswick                 753.3     755.5     755.6     756       756.7
Quebec                        7323.6    7351.2    7381.8    7417.7    7455.2
Ontario                       11387.4   11527.9   11697.6   11894.9   12068.3
Manitoba                      1137.9    1142.5    1146.4    1149.1    1150.8
Saskatchewan                  1024.9    1025.6    1022      1017.1    1011.8
Alberta                       2906.8    2959.6    3009.9    3059.1    3113.6
British Columbia              3997.1    4028.3    4060.1    4101.6    4141.3
Yukon                         31.5      31.1      30.6      30.2      29.9
Northwest Territories         41.1      41        40.8      41.2      41.4 
Nunavut                       26.4      26.9      27.5      28.1      28.7

这是我的代码:

double year[] [] = new year [13] [5];
BufferedReader x = new BufferedReader (new FileReader ("populationByProvnices.txt"));

我试图用上面文本文件中的数字填充年份数组,谢谢你:D

1 个答案:

答案 0 :(得分:0)

您可以使用bufferedreader和嵌套for循环的组合从文本文件填充二维数组。这样的事情可以解决问题:

        BufferedReader bf = new BufferedReader (new FileReader (new File ("populationByProvinces.txt")));
        provinceList = new ArrayList ();
        year = new double [13] [5];
        String line = "";
        for (int x = 0 ; x <= 12 ; x++)
        {
            line = bf.readLine ();
            provinceList.add (line);

            for (int y = 0 ; y <= 4 ; y++)
            {
                year [x] [y] = Double.parseDouble ((line.substring ((y * 10 + 30), (y * 10 + 38))));
            }
        }
        bf.close ();