0

I am struggling with a school assignment and part of the assignment requires me to insert an empty array into a method and then return it with random values inside and then print the array in the main method. The error I get is the ArrayIndexOutOfBoundsException and I thought of using try catch in the method but it doesn’t work.

int[] genarator(int[] arr){
    
        int maxValues=10;
        int pointer=0;
    Random r=new Random(); //I am not sure the 
    if(arr[maxValues] !=0) {
        return arr;
    }
    for(int i=0;i<maxValues;i++) {
        arr[pointer] = r.nextInt((10 - 0) + 1);
        pointer++;
    }
    return arr;
}

1 Answers1

0
`arr[maxValues]`

You said that you have to pass an empty array The error occurs because you try to get the 10-th element of an empty array, which doesn't exist Try arr = new int[maxValues]; before the if(arr[maxValues] !=0) line