打印抛硬币次数与正面和反面图表的抛硬币模拟器 (Java)

Coin tossing simulator that prints a chart of # of tosses vs heads and tails (Java)

所以我正在做一个问题,需要我用 math.random 模拟抛硬币。我建立了一种方法来使用数组计算硬币正面和反面的次数,但现在我需要以 :

的形式打印出 table

投掷次数-----正面-----反面

10
.

.

.

1000000

我该怎么做呢?任何提示将不胜感激。这是我目前的代码:

 public static void main(String[]args){
    int[] Coin_Toss = {0,0};
    
   
  
    int flip1 = 10;
   /* int flip2 = 100;
    int flip3 = 1000;
    int flip3 = 10000;
    int flip4 = 100000;
    int flip5 = 1000000; */

   


   for(int i = 0; i < flip1; i++)// Tallys coin flips into array for Flip ;
   { 
    Toss(Coin_Toss);
   
   }
  

   System.out.printf("%s\t%s\t%s","# of Tosses","# of Heads","# of Tails");
  for(int i = 0; i< 1; i++) // Print out tallied array
  {
      System.out.printf("\n%d\t\t%d\t\t%d",flip1,Coin_Toss[0],Coin_Toss[1]);
  }

}


public static int Toss(int[] a){// method to simulated coin toss
   
    int num = (int)(Math.random()*2);
    if (num == 0){
        a[0]++;

    }
    else{
        a[1]++;
    }
    
    return num;
}

}

首先,我认为你做错了一件事(即使它有效):

传递对象 Coin_Toss 并在每次迭代中使用它。它之所以有效,是因为您更新了参考内存,但这不是一个好习惯。

如果我明白你想要那样的东西

//Iterate through nFlips (10, 100, 1000 ... )

//Calculate how many times is head or tail

//print

所以此时你需要:

  1. 存储您完成的迭代
  2. 存储结果(头或尾)

方法有很多种。例如,您可以使用具有属性 nIterationsnHeadnTail 的对象来存储数据。

但是,根据您的工作,我认为这是一个更好的解决方案

//Total flips you want to do
int[] flips = { 10, 100, 1000, 10000, 100000, 1000000 };

//List where store the results
List<int[]> results = new ArrayList<int[]>();

//Loop the 'nIterations'
for (int i = 0; i < flips.length; i++) {    
    results.add(Toss(flips[i])); //<-- call method to get the results and store in ArrayList
}
//Print the result
System.out.printf("%s\t%s\t%s", "# of Tosses", "# of Heads", "# of Tails");
for (int i = 0; i < results.size(); i++) // Print out tallied array
{
    System.out.printf("\n%d\t\t%d\t\t%d", flips[i], results.get(i)[0], results.get(i)[1]);
}

抛硬币的方法如下

public static int[] Toss(int nIterations) {// method to simulated coin toss
    //At this point is better create an object and return that instead of use the same one
    int[] coinValues = {0, 0};
    for(int i = 0; i < nIterations; i++) {
        int num = (int) (Math.random() * 2);
        if (num == 0) {
            coinValues[0]++;
        } else {
            coinValues[1]++;
        }
    }   
    return coinValues;
}

仅此而已。

概述:您有一个 'principal' 列表来存储数据。该列表由具有两个位置(第一个头,第二个尾)的整数数组组合而成。 所以迭代你有你需要的所有数据。

我编辑添加控制台输出

# of Tosses # of Heads  # of Tails
10          6           4
100         41          59
1000        503         497
10000       5015        4985
100000      49931       50069
1000000     499940      500060