I'm trying to make a new array out of an existing array based on the value of each element. If a number in the existing array is in the given condition, the number needs to be added to the new array, but the values in the new array are all 0.
What is wrong with this code here?
double[] gpa = {1.0, 2.0, 3.0, 4.0, -1.0, 5.0};
double[] newGpa = null;
for (int i = 0; i < gpa.length; i++) {
if (gpa[i] > 0 && gpa[i] <= 4.0) {
newGpa = new double[i + 1];
newGpa[i] = gpa[i];
}
}
new double[i+1]creates a new array initialized to all zeroes... if you want to resize an array, you have to manually copy the old values into the new array, or perhaps you should use a class likeArrayListthat does it for you automatically.