Scanner input = new Scanner (System.in); Random random = new Random (); int randomInt = random.nextInt (100); int amountOfGuesses = 7; System.out.println("Guess a number between 1 and 100 (no decimals)"); int theUserGuess = input.nextInt(); while (theUserGuess != randomInt && amountOfGuesses>0){ if (theUserGuess < randomInt){ System.out.println("Too low, guess again. Amount of guesses " + amountOfGuesses); amountOfGuesses--; theUserGuess = input.nextInt(); } if(theUserGuess > randomInt){ System.out.println("Too high, guess again Amount of Guesses " + amountOfGuesses); amountOfGuesses--; theUserGuess = input.nextInt(); } if(theUserGuess == randomInt){ System.out.println("Congratulations you won!"); } else if (amountOfGuesses < 1){ System.out.println("Sorry you lose. Play again?"); System.out.print("Answer " + randomInt); } }
JAVA - Guess the Number!
Click 'Run The Code!', bottom right of the editor, to start the game!
Enter Answers in box below the console (after click on 'Run The Code!')
Be patient, while it compiles the code after starting the game!