开发者

Why am I getting array elements with "0"? (See pastie inside)

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 int开发者_开发百科o 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 :)


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.


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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜