Java Reference
In-Depth Information
//Method to roll a die.
//This method uses a random number generator to randomly
//generate a number between 1 and 6, and stores the number
//in the instance variable num and returns the number.
public int roll()
{
num = ( int ) (Math.random() * 6) + 1;
return num;
}
//Method to return the number on the top face of the die.
//Returns the value of the instance variable num.
public int getNum()
{
return num;
}
//Returns the value of the instance variable num as a string.
public String toString()
{
return "" + num;
}
}
We leave the UML class diagram of the class RollDie as an exercise for you.
The following program shows how to use the class RollDie in a program:
// Program to test various operations of the class RollDie.
8
import java.util.*;
//Line 1
public class TestProgRollDie
//Line 2
{
//Line 3
static Scanner console = new Scanner(System.in);
//Line 4
public static void main(String[] args)
//Line 5
{
//Line 6
RollDie die1 = new RollDie();
//Line 7
RollDie die2 = new RollDie();
//Line 8
System.out.println("Line 9: die1: " + die1);
//Line 9
System.out.println("Line 10: die2: " + die2);
//Line 10
System.out.println("Line 11: After rolling "
+ "die1: " + die1.roll());
//Line 11
System.out.println("Line 12: After rolling "
+ "die2: " + die2.roll());
//Line 12
System.out.println("Line 13: Sum of the "
+ "numbers rolled by the dice is: "
+ (die1.getNum() + die2.getNum()));
//Line 13
Search WWH ::




Custom Search