Mihajlo Sljukic
Mihajlo Sljukic

Reputation: 21

Getting Exception in thread "main" Error

So I have array with those numbers and my task is to make 2 new arrays where one array(poz) will have all positive numbers from array and second array(neg) will take all negative values out of array

public class obNiza {
    public static void main(String[] args) {
     int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
     Arrays.sort(array);

     int[] poz= new int[6];
     int[] neg= new int[5];

     for(int i=0; i<array.length; i++)
     { 
         if(array[i] < 0)
             poz[i] = array[i];
         else neg[i] = array[i];
     }

       System.out.println(Arrays.toString(poz));
         System.out.println(Arrays.toString(neg));

    }
}

Upvotes: 0

Views: 49

Answers (3)

Mustafa &#199;il
Mustafa &#199;il

Reputation: 776

Your array size is 13. But poz array's size + neg array's size = 13. In for loop the zero values in array, added to neg array. Because of this throws ArrayIndexOutOfBoundsException. You must delete zero values in array. Because zero is neither positive nor negative.

To delete a value from an array you can use ArrayUtils class.

For example: array = ArrayUtils.removeElement(array, element)

commons.apache.org library:Javadocs

Upvotes: 0

lospejos
lospejos

Reputation: 1986

IMHO you could use List (ArrayList):

import java.util.*;

public class ObNiza {
    public static void main(String[] args) {
    int[] array = {12, 23, -22, 0, 43, 545, -4, -55, 43, 12, 0, -999, -87};
    Arrays.sort(array);

    List<Integer> positivesList = new ArrayList<>();
    List<Integer> negativesList = new ArrayList<>();

    for(int i=0; i<array.length; i++) { 
        if (array[i]==0) { // since 0 is not negative nor positive 
            continue;
        }
        if(array[i] < 0) {
            positivesList.add(array[i]);
        } else {
            negativesList.add(array[i]);
        }
    }

    Integer[] poz = positivesList.toArray(new Integer[positivesList.size()]);
    Integer[] neg = negativesList.toArray(new Integer[negativesList.size()]);

    System.out.println(Arrays.toString(poz));
    System.out.println(Arrays.toString(neg));

    }
}

Upvotes: 1

achAmh&#225;in
achAmh&#225;in

Reputation: 4266

As you don't know in advance the amount of positive and negative numbers, you're better off using an ArrayList.

ArrayList<Integer> poz = new ArrayList<>();
ArrayList<Integer> neg = new ArrayList<>();

Then loop through and add to the relevant ArrayList as needed

for (int i = 0; i < array.length; i++) {
            if (array[i] > 0) {
                poz.add(array[i]);
            } else {
                neg.add(array[i]);
            }
        }

Note: change array[i] > 0 to array[i] >= 0 if you want 0s to go into poz

Output:

[12, 12, 23, 43, 43, 545]

[-999, -87, -55, -22, -4, 0, 0]

Upvotes: 1

Related Questions