Use nextInt(int num)
to select numbers from the range 0 through 5, then
add one:
die = rand.nextInt(6)+1;
The trick is to determine how many integers are in the range of outcomes you want, and
use that as the parameter to nextInt()
.
Then add the minimum value of the range you want.
If you want integers in the range min
up to and including max
do this:
num = rand.nextInt(max-min+1) + min;
In this example we want 1,2,3,4,5,6 so the number of outcomes is 6.
nextInt(6)
will output numbers from 0,1,2,3,4,5 so add one to get
the desired range.
Here is a program that simulates tossing a die.
import java.util.Random; import java.util.Scanner; public class DieToss { public static void main ( String[] args ) { Scanner scan = new Scanner( System.in ); Random rand = new Random( ); while ( true ) { System.out.print("You toss a " + (rand.nextInt(6)+1) ); String line = scan.nextLine(); } } }
The statement:
Random rand = new Random();
creates a random number generator using a seed based on the current time. The program will produce a different sequence of numbers each time it is run.
The while
loop runs until the user hits control-C (or otherwise kills the program).
The loop body
selects a random number from the range 1 through 6 and prints it out:
System.out.print("You toss a " + (rand.nextInt(6)+1) );
Then the loop body waits until the user hits "enter". (Actually, any line followed by "enter" will work.)
String line = scan.nextLine();
Nothing is done with the line the user types; it is just used to pause the output. (You could improve the program by having it end gracefully when the user types "Q" or "q".)
Say that you want random integers in the range -5 to +5 (inclusive).
How can you use nextInt()
for that? (Hint: see the previous answer.)