0

I have been trying to write a method that when called upon will produce an array of a random length with random numbers assigned to each value. For some reason, I am getting an out of bounds exception inside the for-loop.

   public static int[] randArray()
   {
       int[] myRandArray = new int[0];
       
       for (int i = 0; i <= (int)((Math.random() * 99) + 1); i++ ) {
           myRandArray[i] = (int)((Math.random() * 99) + 1);
       }
       
       return myRandArray;
   }

I'm very much so a newbie to Java and this is probably a dumb question but thanks anyways.

1
  • You made a zero-length array. You should take an input (e.g. a method parameter) for how big the array should be when you call new int[SIZE]. If you don't want to specify it via a passed value, then made use of the rng inside of the array initialization (to create something bigger than 0), then use myRandArray.length like usual. Commented Mar 8, 2021 at 2:21

3 Answers 3

1

You need to set the final array length before you try to add to it:

int length  = (int)((Math.random() * 99) + 1);
int[] myRandArray = new int[length];

Then inside the loop you can simply do:

for (int i = 0; i < length; i++ ) {
    myRandArray[i] = (int)((Math.random() * 99) + 1);
}

Note how in the loop I use i < not i <= , otherwise the last item will be out of bounds.

Sign up to request clarification or add additional context in comments.

Comments

0

You have already defined an array with size 0

int[] myRandArray = new int[0];

Now if you insert any element into this array you will find yourself Index out of bound every time.

Instead use Dynamic array such as ArrayList or else you can do below adjustments.

int[] myRandArray = new int[(int)((Math.random() * 99) + 1)];

and loop through the length of array.

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

Comments

0

Solution:

// create a random length
int len = (int)((Math.random() * 99) + 1);
int[] array = new int[len];

// add random values to the array
for (int i = 0; i < len; i++) {
    array[i] = (int)((Math.random() * 99) + 1);
}
System.out.println(Arrays.toString(array));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.