1
package javaapplication1;

/**
 *
 * @author
 */
public class JavaApplication1 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        int[] scores = {1,2,3,4,5,6};
        int[] fin = extractAllEvens(scores);
        for(int i =0; i<fin.length; i++) {
            System.out.println(fin[i]);
    }
    }
        public static int[] extractAllEvens(int[]scores) {
            int evenCount = 0;
            for (int i =0; i<scores.length; i++) {
                if (scores[i] % 2 ==0) {
                    evenCount++;
                }
        }
        int[] newScores = new int[evenCount];
        int j = 0;
        for(int i = 0; i<scores.length; i++) {

            if(scores[1] % 2 ==0) {
            newScores[1] = scores[i];
            j++;
            }
        }
    return newScores;
}
}

I'm trying to output 2, 4, 6.

But I keep getting results such as 0,6,0.

I think I messed up somewhere with the variables with i or j or the number 1 and possibly their locations... can anyone help lead me in the right direction?

0

4 Answers 4

1

scores[1] % 2 == 0 and newScores[1] = scores[i]?

You have hard-coded to use only index 1 (the second element) of newArray.

You probably should be using j as the index instead of 1.

Sign up to request clarification or add additional context in comments.

Comments

0

Your last loop uses 1 as fixed loop index.

Change that to i instead.

2 Comments

ummm one should be i and other one j :)
You are right. And the real take away us:the op should try writing less confusing code in the first place :-)
0

Change the second for loop like this -

for (int i = 0; i < scores.length; i++) {
        if (scores[i] % 2 == 0) {
            newScores[j] = scores[i];
            j++;
        }
    }

Cheers!

Comments

0

instead of

if(scores[1] % 2 ==0) {
        newScores[1] = scores[i];

It should be

if(scores[i] % 2 ==0) {//← i here
        newScores[j] = scores[i];//← j here

O/P : 2 4 6

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.