programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Random number

King-Chieh Wang
Greenhorn
Posts: 24
Dear All,
How do I create a random number range inbetween [5,10]?
Jack

Sanyev Babu
Ranch Hand
Posts: 132

The code above uses the random methord in the java.lang.Math class it generates a double random number between 0 and 1 including 0 and excluding 1. You can multiply the number with 5 and then add 5 to it to obtain a randum number between 5 and 10. Note that the number generated will be a double number if you want it to be int you must down cast it.

Sanyev Babu
Ranch Hand
Posts: 132
Sorry the code
public void amethord()
{ System.out.println("amethord");
}
in my above post is not needed. I was working with some other example which needed that methord. I modified that file to make the example. Sorry for that.

Vicken Karaoghlanian
Ranch Hand
Posts: 522
Sanyev-
In regards to your second post, you can always edit your first post instead of creating a new one.
King-Chiehm-
Although the solutions posted by Sanyev is correct however it is not accurate because the number 10 will never be reached, the closest number you'll get is 9.9999999.
So technically speaking, [5,10) will describe the answer more accurately.
[ March 09, 2004: Message edited by: Vicken Karaoghlanian ]

Carlos Failde
Ranch Hand
Posts: 84
java.util.Random random = new java.util.Random();
int n = 5 + random.nextInt(6);
nextInt(6) returns numbers between 0 inclusive and 6 exclusive

Sanyev Babu
Ranch Hand
Posts: 132

The above code will generate integer random numbers in the interval [5,10] both inclusive. Note that the random number in the interval [0,1) is multipled with 6 so we will get numbers in the range [0,6). Adding five to the value will bring the value to [5,11). As the result is a double value casting it to an int will bring the value to [5,10] since casting to int will truncate the decimal value rather than round the number.

 It is sorta covered in the JavaRanch Style Guide.