我是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或更多。 请问,有人对此有任何解决方案吗?我哪里错了? 感谢
答案 0 :(得分:2)
不是将结果附加到字符串中,然后将字符串拆分并计算&#34; Head&#34; /&#34; Tail&#34;的出现次数。你可以在单独的变量中跟踪计数:
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);
}
答案 1 :(得分: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));