user4556228
user4556228

Reputation:

Out of bounds, why?

I've discovered strange (at least for me) exception throw. Let me make it short enough. There is a method which returns an array with random values. In main method I use foreach loop to show every value stored in my array.

tab[i] = (int) ((Math.random()*10));

It works fine until I set the minimum value.

tab[i] = (int) ((Math.random()*10)+1);

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10

Could someone explain this to me? I have no clue how does +1 on right side affect size of array.

Edit: Full code

import java.lang.Math;

public class Arrays {

    static private int[] makeArray(int wide) {

        int[] tab = new int[wide];

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

        return tab;
    }

    public static void main(String[] args) {
        int tabby[] = makeArray(10);

        for(int i : tabby) {
            System.out.println(tabby[i]);
        }

    }

}

Upvotes: 1

Views: 93

Answers (1)

Lucas Ross
Lucas Ross

Reputation: 1089

for (int i : tabby) is giving you the values in the tabby array, not the indexes (zero through nine) of the array. Just do System.out.println(i).

edit: To elaborate, you should be seeing this program throw the exception intermittently because your random number assignment has a one in ten chance of producing the number 10, and tabby[10] is going to be out of bounds.

Upvotes: 4

Related Questions