lundi 26 octobre 2020

Guessing game with integer input validation and number of right guessed answers displayed Java

I'm building a dice guessing game. the program has 5 die tosses. I've implemented hasNextInt() as it is the only one I can understand at the moment.

  1. When I enter something that's not an Int it breaks out of the code but I want the program to continue for the rest of the goes (out of 5).
  2. Also If the user guesses correctly I have to keep track of how many they get right.
  3. If they guess wrong I have let them know what the die toss was, this keeps returning the first wrong die toss for the five goes.
  4. At the end I have let the player know how many they got right out of 5.

This is my code so far

import java.util.Scanner;

public class Attempt11
{
    public static void main(String args[]) {
        int attempt = 1;
        int userGuessNumber = 0;
        int secretNumber = (int) (Math.random() * 6) + 1;
        Scanner userInput = new Scanner(System.in);
        System.out.println("Guess the next dice throw (1-6)");

        do {
            if (userInput.hasNextInt()) {
                userGuessNumber = userInput.nextInt();

                if (userGuessNumber == secretNumber) {
                    System.out.println("Congratulations you guessed right");
                    continue;
                } else if (userGuessNumber < 1) {
                    System.out.println("Number must be between 1 and 6 inclusive, please try again ");
                } else if (userGuessNumber > 6) {
                    System.out.println("Number must be between 1 and 6 inclusive, please try again ");
                } else if (userGuessNumber > secretNumber) {
                    System.out.println("Hard luck the last throw was " + secretNumber);

                } else if (userGuessNumber < secretNumber) {
                    System.out.println("Hard luck the last throw was " + secretNumber);
                }
                if (attempt == 5) {
                    System.out.println("You have exceeded the maximum attempt. Try Again");
                    break;
                }
                attempt++;
            } else {
                System.out.println("Enter a Valid Integer Number");
                break;
            }
        } while (userGuessNumber != secretNumber);
        userInput.close();
    }
}



Aucun commentaire:

Enregistrer un commentaire