Java out of bounds error?

Subscribe to Java out of bounds error? 6 posts

avatar for LunarLady LunarLady 7 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.

 
avatar for OctaBech OctaBech 23 posts
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.

 
avatar for vesperbot vesperbot 1846 posts
Flag Post

The code provided does not contain line #11.

 
avatar for LunarLady LunarLady 7 posts
Flag Post

Thank you Octa, It works brilliantly now.

 
avatar for vesperbot vesperbot 1846 posts
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???

 
avatar for OctaBech OctaBech 23 posts
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.