# Updated guessing game

6th October 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.

This is the new version which has a couple of fixes: 1) it only asks to play again after the game has ended 2) the number of guesses resets if the player plays again. Also, I'll change the formatting later.

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) {
while(true) {
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")) {
numberOfGuesses = 3;
} else {
runMainLoop = false;
}
}

}

public static int getNumber() {

while(true) {
try {
return sc.nextInt();
} catch (InputMismatchException e) {