Dice Rolling Simulation Program
This Java program simulates the rolling of a dice. Each time you run the program, it generates a random number between 1 and 6, which represents the face of a dice.
Program Structure
- Main Class: DiceRoller
- Main Method: The main method is the entry point of the program. It creates an instance of the DiceRoller class and calls the rollDice method.
- rollDice Method: This method generates a random number between 1 and 6 using the Random class and prints the result to the console.
Java Code
import java.util.Random;
/**
* The DiceRoller class simulates the rolling of a dice.
*/
public class DiceRoller {
/**
* The main method is the entry point of the program.
* @param args Command line arguments
*/
public static void main(String[] args) {
// Create an instance of DiceRoller
DiceRoller roller = new DiceRoller();
// Call the rollDice method
roller.rollDice();
}
/**
* This method simulates rolling a dice by generating a random number between 1 and 6.
*/
public void rollDice() {
// Create an instance of Random
Random random = new Random();
// Generate a random number between 1 and 6
int diceFace = random.nextInt(6) + 1;
// Print the result
System.out.println("You rolled a " + diceFace + "!");
}
}
Explanation
The program starts by importing the java.util.Random class, which is used to generate random numbers. The DiceRoller class contains the main method, which is the entry point of the program. Within the main method, an instance of the DiceRoller class is created, and the rollDice method is called.
The rollDice method generates a random number between 1 and 6 using the nextInt method of the Random class. The nextInt(6) method generates a random number between 0 and 5, so 1 is added to the result to get a number between 1 and 6. Finally, the result is printed to the console.
