-1

I am trying to convert an array containing int data type to an array containing boolean data type. My method must be able to check whether the number is even or not and then store it as "true" if even or otherwise "false". The return type must a boolean array. How do I do this? The code I wrote apparenty doesn't work and I do not really understand why. Actually the error I get is ArrayIndexOutOfBoundsException: Index 12 out of bounds for length 6 (my original array has indeed 6 elements). Can someone please tell me why? I am using Java 8.

 public static boolean[] evenNumbers ( int[] array){
            boolean[] array1= new boolean[array.length];
            for (int i: array) {
                if(array[i]%2==0){
                    array5[i]=true;
                }
            }
            return array5;
        }

Thank you very much!

Msitake
  • 13
  • 2

3 Answers3

4

In your loop, i is the element’s value, not its index, and so is likely to not be a valid index.

Change your foreach loop to a conventional for loop:

boolean[] result = new boolean[array.length];
for (int i = 0; i < array.length; i++)  {
    result[i] = array[i]%2==0;
}
return result;
Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

Can someone please tell me why?

In the for loop

for (int i: array) {

you're not using the indices, but the elements.

Use the traditional for instead, as foreach was meant to hide the iterator.

for(int i = 0; i < array.length; i++) {
    
}
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
0

A stream-based solution (though returning Boolean[]) would be:

public static Boolean[] evenNumbers ( int... array) {
    return IntStream.range(0, array.length)
                    .mapToObj(i -> array[i] % 2 == 0)
                    .toArray(Boolean[]::new);
}
System.out.println(Arrays.toString(evenNumbers(1, 2, 3, 4, 5, 6, 5, 3, 1, 2)));

Output:

[false, true, false, true, false, true, false, false, false, true]
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42