'Writing into an array
I have a method that needs to get years from an object and write that into an array. This is what I have so far:
public int[] getYears() {
int[] years = null;
for (RainfallYear rainfall : rainfallYears) {
int year = rainfall.getYear();
//insert year into int[] years array and return.
}
return years;
}
-
RainfallYear is an object that takes in a year and the values for rainfall during the months of the year:
public RainfallYear(int year, double[] rainfallMonths) {
super();
this.year = year;
this.rainfallMonths = rainfallMonths;
}
This is how it would look like visually:
1914,50.9,87,115.8,32.3,47.1,56.6,97.1,63.9,48.1,62.4,110.3,190.8
rainfallYears is the name of an array of RainfallYear objects:
private RainfallYear[] rainfallYears = null;
I am struggling to insert the "extracted" year into an array to achieve the functionality of the int[] getYears method - to return an array of years.
Here is my previous attempt at doing this, but I don't think what I did was correct:
List<Integer> yearsList = null;
for (int i = 0; i < rainfallYears.length; i++) {
yearsList = new ArrayList<Integer>();
yearsList.add(new RainfallYear(i, null).getYear());
}
int[] yearsArray = new int[yearsList.size()];
for (int i = 0; i < yearsList.size(); i++) {
yearsArray[i] = yearsList.get(i);
}
return yearsArray;
Solution 1:[1]
You are reinitializing your yearsList every iteration of the loop which will give it new data each time.
List<Integer> yearsList = null;
for (int i = 0; i < rainfallYears.length; i++) {
yearsList = new ArrayList<Integer>();
yearsList.add(new RainfallYear(i, null).getYear());
}
Instead, initialize your list outside of the loop like you did for your array.
List<Integer> yearsList = new ArrayList<Integer>();
for (int i = 0; i < rainfallYears.length; i++) {
yearsList.add(new RainfallYear(i, null).getYear());
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jb. |
