RatikBhat
RatikBhat

Reputation: 61

Input Values in Integer Arrays in JAVA

So here's the deal I was messing around with Java trying to make a programme that would take a given int[] and make another int[] which would be in ascending order... so here the code:

import java.util.*;

public class Accending_order {
    public static void main(String args[]) {
        int[] dArray = {
            1, 34, 25, 67, 35, 68, 88
        };
        int[] oArray = new int[200];
        int[] countOf = new int[200];

        for (int i = 0; i < dArray.length; i++) {
            int NumForLoop = dArray[i];
            for (int j = 0; j < dArray.length; j++) {
                int diff = 0;
                if (j != i) diff = NumForLoop - dArray[j];
                if (diff < 0) countOf[i]++;
            }
            for (int k = 0; k < dArray.length; k++) {
                oArray[k] = dArray[dArray.length - countOf[k]];
            }
            for (int i2 = 0; i2 < oArray.length; i2++) {
                System.out.print(oArray[i2]);
            }

        }
    }
}

and this the ERROR it's showing :

 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at Accending_order.main(Accending_order.java:19)

so help.....

Upvotes: 0

Views: 46

Answers (1)

Dima
Dima

Reputation: 8652

the problem is here

 oArray[k] = dArray[dArray.length - countOf[k]];

when countOf[k] = 0, you are trying to access dArray[dArray.length] and dArray.length is 7, but your array contains elements at indexes 0..6

Upvotes: 3

Related Questions