Domanda

I'm trying to fill a two dimensional array with data from text file. Here's the text file:

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

Here is my code:

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

i'm trying to fill the year array with the numbers from the text file above, thank u :D

È stato utile?

Soluzione

You can populate a 2d array from a text file by using a combination of a bufferedreader and a nested for loop. Something like this will do the trick:

        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 ();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top