1

我是Java的初学者,仍然对Java充满热情。我得到了这个练习:“编写一个掷硬币的模拟器程序:一千次然后打印出你得到多少次反面和多少次你得到正面”这就是我迄今为止尝试做的事情。

import java.util.Random; 
import java.util.regex.Pattern; 

public class coin { 

    public static void main( String [] args ) { 

        Random r = new Random(); 
        Pattern tail = Pattern.compile("Tail+"); 
        Pattern head = Pattern.compile("Head+"); 
        String flips = ""; 

        for (int i = 0; i < 1000; i++) { 
            flips += r.nextInt(100) % 2 == 0 ? "Head" : "Tail"; 
        } 
        String[] heads = head.split( flips ); 
        String[] tails = tail.split( flips ); 
        //Display
        System.out.println("Times head was flipped:" + heads.length); 
        System.out.println("Times tail was flipped:" + tails.length); 
    }
}

该程序似乎正在运行,但它总是给我几乎一对正面和反面,总数超过 1000,至少超过 1 个或更多。拜托,有人对此有任何解决方案吗?我哪里错了?谢谢

4

2 回答 2

4

无需将结果附加到字符串中,然后拆分字符串并计算“头”/“尾”的出现次数,您只需在单独的变量中跟踪计数:

int headCount = 0;
int tailCount = 0;

for (int i = 0; i < 1000; i++) {
    if(r.nextInt(100) %2 == 0)
    {
      headCount++;
    }
    else
    {
      tailCount ++;
    }

  System.out.println("Times head was flipped:" + headsCount); 
  System.out.println("Times tail was flipped:" + tailCount); 

}
于 2014-04-11T18:22:51.800 回答
1

硬币有两个面,所以我真的不明白为什么你会要求随机生成器生成一个介于 0 和 100 之间的数字(不包括)。在 0 和 2(不包括)之间会更合乎逻辑。

另外,你被要求数数。附加字符串然后拆分以获得最终值是一种非常复杂且低效的计数方式。您应该改用整数。每次从随机数中获得 1 时,增加一个计数器。最后,您有返回 1 的次数,因此 0 的数量是 1000 - 这个数字。

    Random r = new Random(); 
    int heads = 0;
    for (int i = 0; i < 1000; i++) { 
        int side = random.nextInt(2);
        if (side == 1) {
            heads++;
        } 
    } 
    System.out.println("Times head was flipped:" + heads); 
    System.out.println("Times tail was flipped:" + (1000 - heads)); 

它甚至可以简化为以下内容(尽管这种简化使代码更难理解):

    Random r = new Random(); 
    int heads = 0;
    for (int i = 0; i < 1000; i++) { 
        heads += random.nextInt(2);
    } 
    System.out.println("Times head was flipped:" + heads); 
    System.out.println("Times tail was flipped:" + (1000 - heads)); 
于 2014-04-11T18:25:03.723 回答