简体   繁体   中英

Coin flip method advice

I was assigned to create a method that simulates flipping a coin. I think my code here is pretty solid, only I can't get it to show a series of results after n number of flips. So instead of showing HTHHHTTTHTT, I'm only getting H or 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;
}

You iterate over numFlips times, but in each iteration, you call either result = "H"; or result = "T"; . This sets the value of result to either "H" or "T" .

Instead, you should append it. You can do this by calling result += "T"; , or you can use a StringBuilder and call stringBuilder.append("T"); .

You have to move random generation into the loop so the chance is recalucalted for each throw. Something like

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();
    }

That way you won't get 10 of the same.

Plus your int chance argument in

flipCoin(int chance, int numFlips)

is redudant, beacuse you override it with

chance = rando.nextInt();

later in the code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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