1

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];
    }
}
2
  • 1
    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 like ArrayList that does it for you automatically. Commented Sep 16, 2014 at 3:52
  • possible duplicate of Resize an Array while keeping current elements in Java? Commented Sep 16, 2014 at 3:54

3 Answers 3

1

I might suggest this:

 double[] gpa = {1.0, 2.0, 3.0, 4.0, -1.0, 5.0};
 //create a new array with one index less 
 double[] newGpa = new double[gpa.length - 1];
 for (int i = 0; i < gpa.length; i++) {
    if (gpa[i] > 0 && gpa[i] <= 4.0) {
       newGpa[i] = gpa[i];
    }
 }

But it would be smarter to use a dynamic data structure like and an ArrayList and then transform it to an array after processing it using the method below.

 newGpa = list.toArray(new String[list.size()]);
Sign up to request clarification or add additional context in comments.

Comments

0

You are reinitializing the array variable newGpa inside the for loop.

newGpa = new double[i+1];

That is why you are getting all zeros. Either use an ArrayList or resize array properly (allocate a temporary array of length i+1, copy values from newGpa, and then reassign the temp array to newGpa)

double[] gpa= {1.0,2.0,3.0,4.0,-1.0,5.0};
ArrayList<Double> newGpa= new ArrayList<Double>();

for(int i =0; i<gpa.length; i++){
 if (gpa[i] > 0 && gpa[i] <= 4.0){
    newGpa.add(gpa[i]);        
 }
}

Then you can get the array out of ArrayList.

Double[] result = newGpa.toArray(new Double[0]);

Comments

0

Let's look at this line:

        newGpa = new double[i + 1];

After each conditional checking is performed ( gpa[i] > 0 && gpa[i] <= 4.0), There are a brand new array named newGpa created, then all elements of newGpa equals 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.