2016-04-30 47 views
-1

所以,现在我编辑的代码,当有四个时,计算行中的头数和五个连续时的头数。我有以下代码可以正确运行,但它只计算四个数字而不是五个数字。谁能帮我?我复制并粘贴了我的代码之后运行的结果。硬币翻转代码 - 试图数出字符串输出

public class Flip { 

    public static void main(String[] args) 
    { 
     final int FLIPS = 100; 
    int heads = 0; 
    int consecCountfour = 0; 
    int consecCountfive = 0; 
    System.out.println("Trail Tosses:"); 
    for (int i = 1; i<= FLIPS; i++) 
    { 
    if (Math.random() < 0.5) { 
    System.out.print("h"); 
    heads++; 
    } 
    else {    
     System.out.print("t"); 
    if (heads == 4) { consecCountfour++; } 
    heads = 0; 

    if (heads == 5) { consecCountfive++; } 
    heads = 0; 
    } 



    } 
    System.out.println("\n"); 
    System.out.print("Count hhhh:"+ consecCountfour); 
System.out.print("  Count hhhhh:" + consecCountfive); 
    } 
} 
+3

'诠释头= 0;'硬币过来的头:'首长++;' – Laurel

+1

你需要一些变量与第一 –

+0

算我怎么能做出HS和TS可数如果是有道理的?我需要写些什么才能使结果成为字符串 – Alex

回答

0

一个不错的解决方案是计算连续的磁头数量,当尾部被翻转时,连续的磁头数量被设置回0。

final int FLIPS = 100; 
int heads = 0; 
int consecCount = 0; 
for (int i = 1; i<= FLIPS; i++) 
{ 
    if (Math.random() < 0.5) { 
     System.out.print("h"); 
     heads++; 
    } 
    else {    
     System.out.print("t"); 
     if (heads == 4 || heads == 5) { consecCount++; } 
     heads = 0; 
    } 
} 
System.out.print(consecCount); 
+0

谢谢代码很好地符合!我怎么能打印连续的“hhhh”和“hhhhh”的数量? – Alex

+0

@Alex将h和t分为两个不同的字符串,然后使用.length()作为值。 –

+0

@Alex变量可能有点误导,但headCount会计算“hhhh”和“hhhhh”的数量。使用headCount变量的打印功能显示四个和五个连续的头部翻转的数量。 – Clint