硬币投掷类每次返回同一侧

时间:2013-11-18 22:07:02

标签: java random

我需要帮助。我应该投掷掷硬币40次,并且每次都是头部和尾部计数,但由于某种原因,它不断返回所有头部或所有尾部,我无法弄清楚为什么。我得到了一个我必须遵循的UML图。它需要一个名为sideUp的私有String,一个名为Coin的public no arg构造函数,一个名为toss的public void方法,以及一个名为getSideUp的String方法。

硬币类:

import java.util.*;
public class Coin {
private String sideUp;

public Coin(){
    toss();
}

public void toss(){
    Random myRand = new Random();
    int face = myRand.nextInt(2);
    if(face == 0){
        sideUp = "heads";
    }
    else{
        sideUp = "tails";
    }
    getSideUp();
}
public String getSideUp(){
    return sideUp;

}
}

CoinDriver:

public class CoinDriver {
public static void main(String[] args){
    Coin coin = new Coin();
    int headsCount = 0;
    int tailsCount = 0;
    for(int i = 1; i <= 40; i++){
        System.out.println(coin.getSideUp());
        if(coin.getSideUp().equals("heads")){
            headsCount++;
        }
        else if(coin.getSideUp().equals("tails")){
            tailsCount++;
        }
    }
    System.out.println("Total number of heads: " + headsCount + "\nTotal number of tails: " + tailsCount);
}
}

2 个答案:

答案 0 :(得分:10)

您只能在构造函数中调用toss(),因此一旦创建它就不会更改它。

toss()循环中的Coin上致电for以获得新结果。

答案 1 :(得分:2)

每次在CoinDriver中迭代for循环体时,您需要确保重新抛出硬币。请尝试这些:

import java.util.*;
public class Coin {

  public String toss() {
    Random myRand = new Random();
    int face = myRand.nextInt(2);
    if (face == 0) {
      return "heads";
    } else{
      return "tails";
    }       
  } 
}

public class CoinDriver {

  public static void main(String[] args){
    Coin coin = new Coin();
    int headsCount = 0;
    int tailsCount = 0;
    for(int i = 1; i <= 40; i++) {

      if (coin.toss().equals("heads")) {
        headsCount++;
      } else {
        tailsCount++;
      }
    }
    System.out.println("Total number of heads: " + headsCount + "\nTotal number of tails: " + tailsCount);
  }
}