簡體   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