掷双骰结果统计(Show statistical data of Craps (Rolling of two dice))

// 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;
     }

 

 }

    
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值