The Game Logic

Get an overview of our game's logic.

The secret number

The game will generate a secret number that our player is supposed to guess. For that, we’ll use Java’s random number generator method, Math.random(). More specifically, we’ll use Math.random() * (max - min + 1) because this lets us specify a range for the random number. For example, if we want to generate a number between 40 and 70, we’ll use Math.random() * (70 - 40 + 1).

Note: The method Math.random() * (max - min + 1) returns a floating number (a number with a decimal), not an integer.

The guess number

Once we’ve generated our secret number, we want the player to guess it. For that, we’ll need the user to give their guess as input. In Java, we can take the user’s input using Scanner.

When we take the input, we’ll have to make sure that the user enters only the integer number and reject invalid input like a character or a double value.

Taking input in Java

Note: We’ll use java.util.Scanner to take the user’s input, but you don’t need to know its details as it is not part of your AP CS A exam.

Let’s see some code for clarity.

Get hands-on with 1200+ tech skills courses.