1

am new to programming and im trying Java, i created this array and gives me this error, task is to count all positive and negative no and place it in new array i called pArr and nArr, and after that to count duplicates and write them and how many times they repeat, can someone help me?

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

        for(int a=0; a<array.length; a++){
            if(array[a]>0)
                brPoz++;
            else if (array[a]<0)
                brNeg++;
        }
        int[] pArr = new int[brPoz];
        int[] nArr = new int[brNeg];     

        for (int i = 0; i < array.length; i++) {
            if (array[i] > 0) {
                pArr[i] = array[i];
            }
        }

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


        Arrays.sort(array);
        Arrays.sort(pArr);
        Arrays.sort(nArr);
        System.out.println(java.util.Arrays.toString(array));
        System.out.println(java.util.Arrays.toString(pArr));
        System.out.println(java.util.Arrays.toString(nArr));


          for (int i = 0; i < array.length; i++) {
            for (int j = i + 1; j < array.length; j++) {
                if ((array[j])==array[i]) {
                    System.out.println("Duplikati su: "+array[j]);
                }
            }
        }
LjubisaK
  • 9
  • 1
  • 8
  • You'll need to come up with a convention for tracking the index of `pArr` and `nArr`, because using `array` is bigger than both of them so `pArr[i]` is out of bounds. – Zircon Dec 21 '16 at 15:22
  • If you use an `ArrayList` this would make this so much easier – Hypnic Jerk Dec 21 '16 at 15:23

1 Answers1

1

What you do is, you first count all positive and negative numbers (BTW: you ignore 0... is that a positive number?). Then you create new arrays based on those counts.

brPoz and brNeg will be less than the element count of the original array. So you need to make sure you only use existing indexes in your resulting arrays.

This could be achieved with

    int pArrIndex = 0;
    for (int i = 0; i < array.length; i++) {
        if (array[i] > 0) {
            pArr[pArrIndex++] = array[i];
        }
    }

    int nArrIndex = 0;
    for (int i = 0; i < array.length; i++) {
        if (array[i] < 0) {
            nArr[nArrIndex++] = array[i];
        }
    }
Florian Heer
  • 694
  • 5
  • 17
  • thank you for help it now stores the values i wanted, and only problem left is duplicate counter, i need to write out how many times does a duplicate number is repeated. – LjubisaK Dec 21 '16 at 17:19