繁体   English   中英

硬币翻转方法建议

[英]Coin flip method advice

我被指派创建一种模拟抛硬币的方法。 我认为我这里的代码非常可靠,只是在 n 次翻转后我无法让它显示一系列结果。 因此,我没有显示 HTHHHTTTHTT,而是只显示 H 或 T。

public static void main(String[] args) {
    System.out.println((flipCoin(2, 10)));

}
    public static String flipCoin(int chance, int numFlips) {
        String result = "";
        Random rando = new Random();
        chance = rando.nextInt();
        for (int i = 0; i < numFlips; i++) {
            if (chance % 2 == 0) {
                result = "H";
            }
            else {
                result = "T";
            }
            numFlips++;
        }
        return result;
}

您迭代numFlips次,但在每次迭代中,您都调用result = "H"; result = "T"; . 这会将result的值设置为"H""T"

相反,您应该附加它。 你可以通过调用result += "T"; ,或者您可以使用StringBuilder并调用stringBuilder.append("T"); .

您必须将随机生成移动到循环中,以便为每次投掷重新计算机会。 就像是

public static String flipCoin(int numFlips) {
            StringBuilder result = new StringBuilder("");
            Random rando = new Random();
            for (int i = 0; i < numFlips; i++) {
                if (rando.nextInt() % 2 == 0) {
                    result.append("H");
                }
                else {
                     result.append("T");
                }
            }
            return result.toString();
    }

这样你就不会得到10个相同的。

加上你的int chance论点

flipCoin(int chance, int numFlips)

是多余的,因为你用

chance = rando.nextInt();

稍后在代码中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM