mardi 23 novembre 2021

Keeping a tally of how many times a number appears using a random number generator. Java

In this code I am writing here the user inputs whether or not they would like to choose heads or tails in a coinflip game. I would like to keep a tally of how many times heads appears or tails appears and output it each time it changes. After hours of trying and searching I cannot figure it our perfectly so if someone could let me know what I could utilize let me know.

import java.util.Random; import java.util.Scanner;

public class CoinToss {

private enum Coin {
    Head, Tail
}

public static void main(String[] args) {
    CoinToss game = new CoinToss();
    game.startGame();


}


private void startGame() {
    Scanner scanner = new Scanner(System.in);
    Coin guess;

    while (true) {
        System.out.print("Enter your guess whether the coin will be heads or tails. Type 1 for heads, 2 for tails, or 3 to quit: ");
        String choice = scanner.nextLine();

        if (choice.equalsIgnoreCase("3")) {
            break;
        } else if (choice.equalsIgnoreCase("1")) {
            guess = Coin.Head;
        } else if (choice.equalsIgnoreCase("2")) {
            guess = Coin.Tail;
        } else {
            System.out.println("Please select either heads tails or quit.");
            continue;
        }

        Coin toss = tosscoin();

        if (guess == toss) {
            System.out.println("You guessed correctly!");
        } else {
            System.out.println("You guessed incorrectly");
        }
    }
    scanner.close();
}


private Coin tosscoin() {
    
    Random r = new Random();
    int sideup = r.nextInt(2);
    if (sideup == 1) {
        
        return Coin.Head;
    } else {
        return Coin.Tail;
    }


}

}




Aucun commentaire:

Enregistrer un commentaire