Guessing game

29th August 2018

This is the Java code for a basic text-based guessing game. The game generates a random number and then asks you to guess a number between 1 and 10. You have three guesses to guess the correct number. If you guess wrong, a new random number is generated.

import java.util.InputMismatchException;
import java.util.Scanner;

public class GuessingGame2 {

    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {

        int guess;
        int random;
        int numberOfGuesses =3;
        String playAgain;
        boolean runMainLoop = true;

        while(runMainLoop) {
            random = (int)(Math.random() * (10 - 1)) + 1;
            System.out.print("Guess a number between 1 and 10: ");
            guess = getNumber();

            if(guess == random) {
                System.out.println("Correct!");
                break;
            } else if(guess > 10){
                System.out.println("The number you entered is bigger than 10");
            }
            else if(guess < 1){
                System.out.println("The number you entered is smaller than 10");
            }
            else {
                numberOfGuesses--;
                System.out.println("Wrong. The number was " + random + ".");
                System.out.println("You have " + numberOfGuesses + " guesses remaining.");
                if(numberOfGuesses == 0) {
                    System.out.println("GAME OVER");
                    break;
                }
            }

            System.out.println("Play again?");
            playAgain = sc.next();
            if(playAgain.equals("y")) {
                System.out.println("k");
            } else {
                runMainLoop = false;
            }
        }
    }

    public static int getNumber() {

        while(true) {
            try {
                return sc.nextInt();
            } catch (InputMismatchException e) {
                System.out.println("Please type an integer.");
                System.out.print("Guess a number between 1 and 10: ");
                sc.next();
            }
        }
    }
}