如何为我的硬币翻转模拟器创建一个硬币?

时间:2015-03-20 03:39:37

标签: java java.util.scanner

我为我的Coin toss模拟器创建了我的Coin类,但是我有几个问题,我错过了什么让它翻转20次(或者是我在程序中编写的东西?)而且,我如何创建一个在我的计划中“硬币”? 这是迄今为止的课程......

   import java.util.Random;
   import java.util.Scanner;

   public class Coin
   {
   private String sideUp;
   private int headCount;
   private int tailCount;

   private Random rand = new Random();

   public void toss()
   {
      sideUp = "";
      headCount = 0;
      tailCount = 0;
      Random rand = new Random();


      //Get random value 0 or 1
      int value = rand.nextInt(2);
      if(value == 0 )
      {
         this.sideUp = "heads";
         headCount++;
      }
      else
      {
         this.sideUp = "tails";
         tailCount++;
      }

   }
   public String getSideUp(String sideUp)
   {
      this.sideUp = "";
      headCount = 0;
      tailCount = 0;
      return sideUp;
   }
   public int getHeadCount(int headCount)
   {
      this.sideUp = "";
      this.headCount = 0;
      tailCount = 0;
      return headCount;
   }
   public int getTailCount(int tailCount)
   {
      this.sideUp = "";
      this.headCount = 0;
      this.tailCount = 0;
      return tailCount;
   }
}

1 个答案:

答案 0 :(得分:2)

您缺少main()方法,这是将代码作为应用程序运行所必需的。请尝试以下方法:

public class Coin {
    // keep your original code...

    public static void main(String[] args) {
        Coin theCoin = new Coin();
        for (int i=0; i < 20; ++i) {
            theCoin.toss();
        }

        System.out.println("Coin was heads " + theCoin.getHeadCount() + " times.");
        System.out.println("Coin was tails " + theCoin.getTailCount() + " times.");

    }
}