Reputation: 11
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?
Upvotes: 1
Views: 51
Reputation: 3166
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
Upvotes: 0
Reputation: 368
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!
Upvotes: 0
Reputation: 409196
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
.
Upvotes: 1
Reputation: 140457
Your last loop uses 1 as fixed loop index.
Change that to i instead.
Upvotes: 0