Example: Here is a Python class that simulates the roll of
five dice, followed by the Java translation.
# DiceRolls Example
# Simulate rolling five dice.
import random
class DiceRolls:
def __init__(self):
self._dice = [0, 0, 0, 0, 0]
self.roll_dice( )
def __str__(self):
output = ''
for i in range(0, 5):
output += str(self._dice[i]) + ' '
return output
def roll_dice(self):
for i in range(0, 5):
self._dice[i] = \
random.randrange(0, 6) + 1
# Main script
d = DiceRolls( )
print(d)
// Java Translation of preceding Python script:
// DiceRolls Example
// Simulate rolling five dice.
import java.util.Random;
public class DiceRolls
{
private Random r;
private int[ ] dice;
public DiceRolls( )
{
r = new Random( );
dice = new int[ ]{0, 0, 0, 0, 0};
this.rollDice( );
}
@Override
public String toString( )
{
String output = "";
for(int i = 0; i < 5; i++)
{
output += dice[i] + " ";
}
return output;
}
public void rollDice( )
{
for(int i = 0; i < 5; i++)
{
dice[i] = r.nextInt(6) + 1;
}
}
public static void main(String[ ] args)
{
DiceRolls d = new DiceRolls( );
System.out.println(d);
d.rollDice( );
System.out.println(d);
}
}