-1

I have an int array. I want to loop thru the 'nums' array and create 2 arrays for odd numbers and even numbers

          int[] nums = {11, 5, 2, 60, 32, 9, 21, 4};

The expected result should be 2 arrays. One array should have even numbers and another array should have odd numbers. but I get outofboundexception error. can't figure out what is wrong

public class ExamReview {
public static void main(String[] args) {


    int[] nums = {11, 5, 2, 60, 32, 9, 21, 4};
    //int[] nums = {11, 5, 2};
    int [] evenArray=  new int[4];
    int [] oddArray=  new int[4];

    int sizeofarray = nums.length;

    for(int i = 0; i< nums.length; i++){

        if(nums[i] %2 == 0) {
            evenArray[i] = nums[i];
        }
        else{
            oddArray[i]= nums[i];
        }

    }
}



        

1 Answers1

1

Issue

When you iterate through your array at the 5th. iteration your i=4 so you try to assign evenArray[4] what is not possible because it has only the length 4 0 1 2 3

evenArray[4] = nums[4]; // _> is out of the arrays boundaries

Solution

Use two different count variables for the position of the two arrays.

import java.util.Arrays;
public class ExamReview {
public static void main(String[] args) {

    
    int[] nums = {11, 5, 2, 60, 32, 9, 21, 4};
    //int[] nums = {11, 5, 2};
    int [] evenArray=  new int[4];
    int [] oddArray=  new int[4];
    int evenCounter = 0;
    int oddCounter = 0;
    int sizeofarray = nums.length;

    for(int i = 0; i< nums.length; i++){

        if(nums[i] %2 == 0) {
            evenArray[evenCounter] = nums[i];
            evenCounter++;
        }
        else{
            oddArray[oddCounter]= nums[i];
            oddCounter++;
        }

    }
      System.out.println(Arrays.toString(evenArray));
      System.out.println(Arrays.toString(oddArray));
      
  }
}

Output

[2, 60, 32, 4]
[11, 5, 9, 21]
Aalexander
  • 4,987
  • 3
  • 11
  • 34