GenericCoin

      STUDY 2007-1-9 18:39

·实验说明:模拟一个银币,此银币有两个面。方法为‘抛银币’,银币顶面、底面随机向上。抛两银币各50次,并显示两银币顶面向上次数和哪个银币顶面次数较多。

·代码:

import java.util.*;
public class GenericCoin {
 private int front;
 private int back;
 
 GenericCoin(){ 
  front=1;
  back=0;
 }//end constructor
 
 public void throwCoin(long coinSeed){
  Random random=new Random(coinSeed);
  front=Math.abs(random.nextInt()%2);
  if(front==0)
   back=1;
  else
   back=0;
 }//end throwCoin
 
 public void setFront(int coinFront){
  front=coinFront;
  back=0;
 }//end setFront
 
 public int getFront(){
  return front;
 }//end getFront
 
 public int getBack(){
  return back;
 }//end getBack
 
 public static void main(String[] args){
  long seed1=System.currentTimeMillis();//set seed
  long seed2=seed1+(new Random()).nextLong()+500;
  int countCoin1=0;
  int countCoin2=0;
  GenericCoin coin1=new GenericCoin();
  GenericCoin coin2=new GenericCoin();
  for(int count=0;count<50;++count){
   coin1.throwCoin(seed1);
   coin2.throwCoin(seed2);
   if(coin1.getFront()==1)
    countCoin1++;
   if(coin2.getFront()==1)
    countCoin2++;
      //System.out.println("front: "+coin1.getFront());
      //System.out.println("back: "+coin1.getBack());
      seed1=seed1+(new Random()).nextLong();
      seed2=seed1+(new Random()).nextLong()+500;
  }
  System.out.println("count coin1:"+countCoin1);
  System.out.println("count coin2:"+countCoin2);
  if(countCoin1>countCoin2)
   System.out.println("The upsides of coin1 is more than" +
     " coin2.");
  else if(countCoin2>countCoin1)
   System.out.println("The upsides of coin2 is more than" +
           " coin1.");
  else
   System.out.println("The upsides of two coin are the same.");
 }

}

·运行结果

count coin1:19
count coin2:21
The upsides of coin2 is more than coin1.

标签集:TAGS:
回复Comments() 点击Count()

回复Comments

{commenttime}{commentauthor}

{CommentUrl}
{commentcontent}