• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Random Number Generator Error

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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)
 
Sheriff
Posts: 11343
Mac Safari Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
reply
    Bookmark Topic Watch Topic
  • New Topic