Die Toss Program

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   hear noise   go to next page

Answer:

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. 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.

Die Toss Program

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( seed );
    
    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 enters a line (any line, including just "enter"),

String line = scan.nextLine();

Nothing is done with the line the user types; it is just used to pause the output. (You could test if the line were "Q" and end the program gracefully, if you wanted.)

QUESTION 6:

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.)