Java out of bounds error?

6 posts

Flag Post

So I have this code

package role.play.generator;
import java.util.Random;
public class RolePlayGenerator {
    public static void main(String[] args) {
        Random randomgenerator = new Random();
        int hairsel = randomgenerator.nextInt()%5;
        String[] haircolours = {"Blue", "Red", "Blonde","Black","Purple"};
        double height = Math.floor(Math.random()*9+58);
        System.out.println("Height is " + height + " Inches");
        System.out.println(haircolours[hairsel]);
    }
}

And I keep getting this error

-2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -2
	at role.play.generator.RolePlayGenerator.main(RolePlayGenerator.java:11)
Java Result: 1

The -2 changes but always stays negative how can I fix this? Every thing else works perfectly.

 
Flag Post

It’s Random.nextInt(5) instead of Random.nextInt()%5. :)

EDIT: Sorry, you probably want to know why.
Random.nextInt() creates a random number using all 32bit, which includes the bit that signs the number to be positive/negative. %5 to a negative number gives a negative result.
Random.nextInt(n) only generates numbers from 0 to n-1.

 
Flag Post

The code provided does not contain line #11.

 
Flag Post

Thank you Octa, It works brilliantly now.

 
Flag Post
Originally posted by OctaBech:

It’s Random.nextInt(5) instead of Random.nextInt()%5. :)

EDIT: Sorry, you probably want to know why.
Random.nextInt() creates a random number using all 32bit, which includes the bit that signs the number to be positive/negative. %5 to a negative number gives a negative result.
Random.nextInt(n) only generates numbers from 0 to n-1.

ummmm, integer mod operation should always return positive value. Or this behavior is different between programming languages???

 
Flag Post

Yeah, both behaviors are mathematically correct, so it’s a decision made by Oracle(Sun) that the result sign is the same as the dividend.