简体   繁体   中英

Why isn't my object storing into an array each time I read a line of a file? Java

I'm reading data in from a text file. Each line has a year at the beginning of the line followed by some data for each month. I'm trying to save both the year and month data into an object and storing it into an object array for each line I read. I'm pretty sure I've done everything right apart from my parseFile method. Here it is -

          while ((line1 = word_reader.readLine()) != null) {
              int year;
              double[] monthlyRain = new double[12];
              String[] values1 = line1.split(",");
              // validation
              if (values1.length == 13){
                  year = Integer.parseInt(values1[0]);

                  for (int i = 1; i < values1.length; i++) { // Start from 1.
                        monthlyRain[i - 1] = Double.parseDouble(values1[i]);
                  }

                  int i =0;
                  rainfallYears[i] = new RainfallYear(year,monthlyRain);
                  i++;
              }
          }     

I thought the lines towards the bottom after the for loop would work but it isn't.

you place your object always at index 0:

int i =0;
rainfallYears[i] = new RainfallYear(year,monthlyRain);

put i outside the while-loop. :

int i = 0;
while ((line1 = word_reader.readLine()) != null) {

then it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM