Two-dice 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:

Yes. Each object of a simulation might need its own random number generator. If you were simulating tadpoles swimming about randomly in pond, you would probably have a random number generator as part of each tadpole object.

Two-dice Program

two dice

Here is a program that simulates the toss of two dice:

import java.util.*;

public class TwoDieToss
{

  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 + rand.nextInt(6)+1) );
      String input = scan.nextLine();
    }
  }
  
}

The two tosses and the sum of the spots is implemented in the expression:

(rand.nextInt(6)+1 + rand.nextInt(6)+1)

Each call to nextInt(6) is completely independent of the previous call, so this is the same as throwing two independent dice.

QUESTION 9:

Would the following work to simulate two dice:

(rand.nextInt(11)+2)