Search code examples
javarandom

Simple Coin Toss using random class in Java. The do while loop doesn't seem to generate random results


I'm having issues generating the random number each time I run through the do-while loop in main. When I remove the do - while statement the if statement works fine and seems to generate a random result each time but when it is repeated in the loop it seems to just repeat the initial result.

Here is my code:

import java.util.Random;

public class CoinToss {
    private enum Coin {Heads, Tails};

    Random randomNum = new Random();
    private int result = randomNum.nextInt(2);
    private int heads = 0;
    private int tails = 1;
    Coin coinFlip;

    public void flip() {
        if (result == 0) {
            coinFlip = Coin.Heads;
            System.out.println("You flipped Heads!");
        } else {
            coinFlip = Coin.Tails;
            System.out.println("You flipped Tails!");
        }
    }
}

And my method main where I seem to be having issues:

import java.util.Scanner;

public class TossGame {
    public static void main(String[] args) {
        CoinToss test = new CoinToss();
        int choice;

        System.out.println("Welcome to the coin toss game!");
        do {
            System.out.print("Enter 1 to toss coin or enter 0 to quit: ");
            Scanner input = new Scanner(System.in);
            choice = input.nextInt();

            if (choice == 1) {
                test.flip();
            } else if (choice > 1) {
                System.out.println("Invalid entry - please enter 1 or 0: ");
                choice = input.nextInt();
            }
        } while (choice != 0);
    }
}

Solution

  • You need to put result inside of flip() method, so it is randomized each call.

    private int result;
    private int heads = 0;
    private int tails = 1;
    Coin coinFlip;
    
    public void flip(){
        result = randomNum.nextInt(2)
        if(result == 0){
            coinFlip = Coin.Heads;
            System.out.println("You flipped Heads!");
        }else{
            coinFlip = Coin.Tails;
            System.out.println("You flipped Tails!");
        }
      }
    }