views:

124

answers:

2

Hey there. Java beginner here :) Well, I'm having a few troubles with this program: http://pastie.org/private/sfqqnqwxtpgtuhswpqepw

1) I want my program to split up the "input" array into an oddList, evenList and negativeList set of arrays. However, when splitting it up, it is adding a bunch of elements as "0".

2) 0 needs to be added only to the oddList.

3) I can't figure out how to add the average from averageAndGreater() to the end of the array.

Thanks :)

+4  A: 

1) Your array is longer than it's contents, since an array is of fixed length, those extra spots must hold something, which is 0.

2) You should add 0 to the even list if possible, because the test for evenness (x%2==0) returns true for 0.

3) You should create the array one longer than you really need int[] oddList = new int[a.length+1]; and use array[array.length-1] = averageAndGreater(input2);

The simplest way to get an array of the right size would probably be to use the ArrayList class built into Java. You could also remake the array at the end of the method when you know how long it needs to be. Like the following:

int array = new int[total];
for (int i=0; i<total; ++i) {
    array[i] = oddList[i];
}

return array;

Edit: Your even and odd lists will include negative numbers, not sure if that was intentional or not, but to reject them use ((a[i] % 2 == 0) && a[i] >= 0) as your even test.

David Kanarek
You're golden, thank you.
alainmeyer1
Happy to help out. Come back if you've got more questions.
David Kanarek
+1  A: 

This is because the length of the array to be returned is initialized to the length of the original array as :

int[] oddList = new int[a.length];
fastcodejava