jQuery in Action, 3rd edition
The moose likes Beginning Java and the fly likes Random Number Generator Error Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Random Number Generator Error" Watch "Random Number Generator Error" New topic

Random Number Generator Error

Rebecca Plumb

Joined: Dec 09, 2007
Posts: 9
I created a class to generate random numbers between 1 & 6. When I run the code I get an exception error:

public final class RandomGenerator{

private RandomGenerator(){

public static int generateRandomNum(int lowerB, int upperB){

if(upperB < lowerB)
return 0;

if(upperB == lowerB)
return lowerB;

return (lowerB + (int) (Math.random() * (upperB - lowerB +1)));

public static void main(String[] args) {

if(args.length < 2 || args.length > 3){

System.out.println("usage: test lowerBound upperBound <repetition>");

int lowerBound = Integer.parseInt(args[0]);
int upperBound = Integer.parseInt(args[1]);
int repetition = 1;
if(args.length == 3)
repetition = Integer.parseInt(args[2]);
for(int i = 0; i < repetition; i ++){

System.out.println("Random number " + i + " = " + generateRandomNum(lowerBound, upperBound));

error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at RandomGenerator.main(RandomGenerator.java:24)

marc weber

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Rebecca Plumb:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at RandomGenerator.main(RandomGenerator.java:24)

This is telling you that at line 24 of RandomGenerator, an array index value of 0 is out of bounds. Line 24 of your code is...

int lowerBound = Integer.parseInt(args[0]);

...so the array is args (the String array used by main). This array will have a length of zero if you don't enter any command line arguments when running the program, so trying to access the first element (args[0]) will result in the exception.

You must enter command line arguments for lower and upper bounds when running this code. For example...

java RandomGenerator 1 6

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
I agree. Here's the link: http://aspose.com/file-tools
subject: Random Number Generator Error
It's not a secret anymore!