-4

I created an array of integers. I tried to return an even array from the original array, but it says "ArrayIndexOutOfBoundsException " pointing at this section of the code "evenArr[size++] = arry[i];". I know d size of d array is 5. Thank you

package practice;

import java.util.*;

class Testt {

    int[] myArr = {4, 6, 6, 7, 2};
    int size = 0;
    int[] evenArr;

    Testt() {
        this.evenArr = new int[size];
    }

    public int[] arr(int[] arry) {
        for (int i = 0; i < arry.length; i++) {
            if (arry[i] % 2 == 0) {
                evenArr[size++] = arry[i];

            }
        }
        return evenArr;
    }
}

public class ReturnStatement {

    public static void main(String[] args) {

        Testt t = new Testt();
        System.out.println("Size: " + t.myArr.length);

        int[] result = t.arr(t.myArr);
        for (int i = 0; i < result.length; i++) {
            System.out.println(result + ", ");
        }

    }

}
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276

1 Answers1

0

In your code, on instantiation, size == 0, so your evenArr has a max size of 0. The second you try to add any value to the array you will get that error. Try making it myArr.size()

Or more ideally, use a list which can be dynamically sized so you don't end up with an oversized array.

zgc7009
  • 3,371
  • 5
  • 22
  • 34
  • why size/2? will not work if more than half the numbers are even; like it is the case for the posted code. and array don't have a `size` method – user85421 Apr 01 '17 at 13:14
  • @CarlosHeuberger cause I half read the question while I was half asleep :P – zgc7009 Apr 01 '17 at 14:40