'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 1:[1]
You only "flipped" once, when you initialized result:
private int result = randomNum.nextInt(2);
When you call flip, get another result:
public void flip(){
result = randomNum.nextInt(2); // Add this line
if(result == 0){
Solution 2:[2]
You need to randomize a flip each time you call flip(), not when CoinToss is constructed:
public class CoinToss {
private enum Coin{Heads, Tails};
Random randomNum = new Random();
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!");
}
}
Solution 3:[3]
if (Math.random() < .5){
System.out.println("Heads");
}else{
System.out.println("Tails");
}
This could be the simplest solution for coin toss.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rgettman |
| Solution 2 | bstar55 |
| Solution 3 | Jency |
