//Show statistical data of Craps (Rolling of two dice)
//Java how to program, 5/e, Exercise 7.15
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
public class DiceRolling extends JApplet implements ActionListener {
int[] diceResult;
double[] possibility;
int rollingTotal;
double possibilityTotal;
JLabel RollingLabel;
JButton RollingButton;
JTextArea output;
DecimalFormat twoDigits=new DecimalFormat("0.000");
public void init()
{
Container container=getContentPane();
container.setLayout(new FlowLayout());
RollingLabel= new JLabel("Press Rolling Button to roll 2 dice 36,000 times");
container.add(RollingLabel);
RollingButton=new JButton("Roll");
container.add(RollingButton);
RollingButton.addActionListener(this);
output=new JTextArea();
container.add(output);
diceResult=new int[12];
possibility=new double[12];
output.append("Sum of two dice\t\tFrequency\tPossibility\n");
}
public void actionPerformed (ActionEvent event)
{
output.setText("Sum of two dice\t\tFrequency\tPossibility\n");
rollingTotal=0;
possibilityTotal=0.0;
for (int i=0;i<11;i++)
diceResult[i]=0;
possibility[i]=0.0;
}
for (int i=0;i<36000;i++)
{
for (int j=0;j<11;j++)
if (rollDice()==j+2)
diceResult[j]++;
rollingTotal++;
}
for (int i=0;i<11;i++)
{
possibility[i]=((double)diceResult[i]/36000);
possibilityTotal+=Double.parseDouble(twoDigits.format(possibility[i]));
output.append(Integer.toString(i+2)+" \t\t"+diceResult[i]+"\t"+
twoDigits.format(possibility[i])+"\n");
}
output.append("Total \t\t"+rollingTotal+"\t"+
twoDigits.format(possibilityTotal)+"\n");
}
public int rollDice()
{
int dice1=(int)(1+Math.random()*6);
int dice2=(int)(1+Math.random()*6);
int sum=dice1+dice2;
return sum;
}

}
发表于 @ 2008年04月17日 12:15:00 | 评论( loading... ) | 举报| 收藏