我是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 个或更多。拜托,有人对此有任何解决方案吗?我哪里错了?谢谢