Cheating Number Guessing Game Java Using Methods

Posted on  by
Cheating Number Guessing Game Java Using Methods Rating: 4,5/5 9877 reviews
  1. Java Random Number Guessing Game
  2. Number Guessing Program Java

We will create a simple guess the number type game. It will choose a random number between 1 and 100, then challenge the player to guess the number in 10 turns. After each turn the player would be told if they are right or wrong — and, if they are wrong, whether the guess was too low or too high. For maximizing the fun I will give you chance to guess the number in 10 chances that means you are going to have 10 number of turns to guess the correct number. Algorithm: Let the computer choose the random number by using this method Math.floor(Math.random. 100) + 1; it will let the machine choose a number between 1 to 100. Coding Up the Guessing Game First, we're going to start by creating a new class, or Java file. Call your new program GuessingGame, keeping the capitalization the same. If you're using Eclipse (and I strongly urge you to!) then make sure to checkmark the box to have it put in your main method for you.

Self-paced training

We offer HTML5, CSS3, JavaScript,Bootstrap, Angular.JS, WordPressNode.JS, React.JS, Joomla, Drupal, Vue.JS and more classes in self-paced video format starting at $60. Click here to learn more and register. For complete self-paced web design training, visit our Web design and development bundle page.

Build a “Guess the Number Game” in JavaScript (beginner level)

Download source files for this recipe

Overview

We will create a simple guess the number type game. It will choose a random number between 1 and 100, then challenge the player to guess the number in 10 turns. After each turn the player would be told if they are right or wrong — and, if they are wrong, whether the guess was too low or too high. It would also tell the player what numbers they previously guessed. The game will end once the player guesses correctly, or once they run out of turns. When the game ends, the player should be given an option to start playing again.
Upon looking at this brief, the first thing we can do is to start breaking it down into simple actionable tasks, in as much of a programmer mindset as possible:

  • Generate a random number between 1 and 100.
  • Record the turn number the player is on. Start it on 1.
  • Provide the player with a way to guess what the number is.
  • Once a guess has been submitted first record it somewhere so the user can see their previous guesses.
  • Next, check whether it is the correct number.
  • If it is correct:
    • Display congratulations message.
    • Stop the player from being able to enter more guesses (this would mess the game up).
    • Display control allowing the player to restart the game.
  • If it is wrong and the player has turns left:
    • Tell the player they are wrong.
    • Allow them to enter another guess.
    • Increment the turn number by 1.
  • If it is wrong and the player has no turns left:
    • Tell the player it is game over.
    • Stop the player from being able to enter more guesses (this would mess the game up).
    • Display control allowing the player to restart the game.
  • Once the game restarts, make sure the game logic and UI are completely reset, then go back to step 1.

Pre-Requisites
Basic computer literacy, a basic understanding of HTML and CSS, an understanding of what JavaScript is.
Learning Objective
To have a first bit of experience at writing some JavaScript, and gain at least a basic understanding of what writing a JavaScript program involves.
To begin with this recipie tutorial, we'd like you to make a local copy of the number-guessing-game-start.html file. Open it in both your text editor and your web browser. At the moment you'll see a simple heading, paragraph of instructions and form for entering a guess, but the form won't currently do anything.
The place where we'll be adding all our code is inside the <script> element at the bottom of the HTML:


<script>

// Your JavaScript goes here

</script>

Let's get started. First of all, add the following lines inside your <script> element:


let randomNumber = Math.floor(Math.random() * 100) + 1;

const guesses = document.querySelector('.guesses');
const lastResult = document.querySelector('.lastResult');
const lowOrHi = document.querySelector('.lowOrHi');

const guessSubmit = document.querySelector('.guessSubmit');
const guessField = document.querySelector('.guessField');

let guessCount = 1;
let resetButton;

This section of the code sets up the variables and constants we need to store the data our program will use. Variables are basically containers for values (such as numbers, or strings of text). You create a variable with the keyword let (or var) followed by a name for your variable (you'll read more about the difference between the keywords in a future article). Constants are used to store values that you don't want to change, and are created with the keyword const. In this case, we are using constants to store references to parts of our user interface; the text inside some of them might change, but the HTML elements referenced stay the same.
You can assign a value to your variable or constant with an equals sign (=) followed by the value you want to give it.
In our example:

  • The first variable — randomNumber — is assigned a random number between 1 and 100, calculated using a mathematical algorithm.
  • The first three constants are each made to store a reference to the results paragraphs in our HTML, and are used to insert values into the paragraphs later on in the code:
  • <p></p>
  • <p></p>
  • The next two constants store references to the form text input and submit button and are used to control submitting the guess later on.
  • <label for='guessField'>Enter a guess: </label><input type='text'>

<input type='submit' value='Submit guess'>

  • Our final two variables store a guess count of 1 (used to keep track of how many guesses the player has had), and a reference to a reset button that doesn't exist yet (but will later).

Note: You'll learn a lot more about variables/constants later on in the course, starting with the next article.
Next, add the following below your previous JavaScript:


function checkGuess() {
alert('I am a placeholder');
}

Functions are reusable blocks of code that you can write once and run again and again, saving the need to keep repeating code all the time. This is really useful. There are a number of ways to define functions, but for now we'll concentrate on one simple type. Here we have defined a function by using the keyword function, followed by a name, with parentheses put after it. After that we put two curly braces ({ }). Inside the curly braces goes all the code that we want to run whenever we call the function.
When we want to run the code, we type the name of the function followed by the parentheses.
Let's try that now. Save your code and refresh the page in your browser. Then go into the developer tools JavaScript console, and enter the following line:

After pressing Return/Enter, you should see an alert come up that says 'I am a placeholder'; we have defined a function in our code that creates an alert whenever we call it.
Note: You'll learn a lot more about functions later in the course.
O
JavaScript operators allow us to perform tests, do maths, join strings together, and other such things.
If you haven't already done so, save your code, refresh the page in your browser, and open the developer tools JavaScript console. Then we can try typing in the examples shown below — type in each one from the 'Example' columns exactly as shown, pressing Return/Enter after each one, and see what results they return. If you don't have easy access to the browser developer tools, you can always use the simple built-in console seen below:
First let's look at arithmetic operators, for example:


Operator

Name

Example

+

Addition

6 + 9

-

Subtraction

20 - 15

*

Multiplication

3 * 7

/

Division

10 / 5

You can also use the + operator to join text strings together (in programming, this is called concatenation). Try entering the following lines, one at a time:


let name = 'Bingo';
name;
let hello = ' says hello!';
hello;
let greeting = name + hello;
greeting;

Java Random Number Guessing Game

There are also some shortcut operators available, called augmented assignment operators. For example, if you want to simply add a new text string to an existing one and return the result, you could do this:

This is equivalent to


name = name + ' says hello!';

When we are running true/false tests (for example inside conditionals — see below) we use comparison operators. For example:


Operator

Name

Example

Strict equality (is it exactly the same?)

5 2 + 4

!

Non-equality (is it not the same?)

'Chris' ! 'Ch' + 'ris'

<

Less than

10 < 6

>

Greater than

10 > 20

C
Returning to our checkGuess() function, I think it's safe to say that we don't want it to just spit out a placeholder message. We want it to check whether a player's guess is correct or not, and respond appropriately.
At this point, replace your current checkGuess() function with this version instead:


function checkGuess() {
let userGuess = Number(guessField.value);
if (guessCount 1) {
guesses.textContent = 'Previous guesses: ';
}
guesses.textContent += userGuess + ' ';
if (userGuess randomNumber) {
lastResult.textContent = 'Congratulations! You got it right!';
lastResult.style.backgroundColor = 'green';
lowOrHi.textContent = ';
setGameOver();
} else if (guessCount 10) {
lastResult.textContent = '!!!GAME OVER!!!';
setGameOver();
} else {
lastResult.textContent = 'Wrong!';
lastResult.style.backgroundColor = 'red';
if(userGuess < randomNumber) {
lowOrHi.textContent = 'Last guess was too low!';
} else if(userGuess > randomNumber) {
lowOrHi.textContent = 'Last guess was too high!';
}
}
guessCount++;
guessField.value = ';
guessField.focus();
}

This is a lot of code — phew! Let's go through each section and explain what it does.

  • The first line (line 2 above) declares a variable called userGuess and sets its value to the current value entered inside the text field. We also run this value through the built-in Number() method, just to make sure the value is definitely a number.
  • Next, we encounter our first conditional code block (lines 3–5 above). A conditional code block allows you to run code selectively, depending on whether a certain condition is true or not. It looks a bit like a function, but it isn't. The simplest form of conditional block starts with the keyword if, then some parentheses, then some curly braces. Inside the parentheses we include a test. If the test returns true, we run the code inside the curly braces. If not, we don't, and move on to the next bit of code. In this case the test is testing whether the guessCount variable is equal to 1 (i.e. whether this is the player's first go or not):

If it is, we make the guesses paragraph's text content equal to 'Previous guesses: '. If not, we don't.

  • Line 6 appends the current userGuess value onto the end of the guesses paragraph, plus a blank space so there will be a space between each guess shown.
  • The next block (lines 8–24 above) does a few checks:
    • The first if(){ } checks whether the user's guess is equal to the randomNumberset at the top of our JavaScript. If it is, the player has guessed correctly and the game is won, so we show the player a congratulations message with a nice green color, clear the contents of the Low/High guess information box, and run a function called setGameOver(), which we'll discuss later.
    • Now we've chained another test onto the end of the last one using an else if(){ } structure. This one checks whether this turn is the user's last turn. If it is, the program does the same thing as in the previous block, except with a game over message instead of a congratulations message.
    • The final block chained onto the end of this code (the else { }) contains code that is only run if neither of the other two tests returns true (i.e. the player didn't guess right, but they have more guesses left). In this case we tell them they are wrong, then we perform another conditional test to check whether the guess was higher or lower than the answer, displaying a further message as appropriate to tell them higher or lower.
  • The last three lines in the function (lines 26–28 above) get us ready for the next guess to be submitted. We add 1 to the guessCount variable so the player uses up their turn (++is an incrementation operation — increment by 1), and empty the value out of the form text field and focus it again, ready for the next guess to be entered.

At this point we have a nicely implemented checkGuess() function, but it won't do anything because we haven't called it yet. Ideally we want to call it when the 'Submit guess' button is pressed, and to do this we need to use an event. Events are things that happen in the browser — a button being clicked, a page loading, a video playing, etc. — in response to which we can run blocks of code. The constructs that listen out for the event happening are called event listeners, and the blocks of code that run in response to the event firing are called event handlers.
Add the following line below your checkGuess() function:


guessSubmit.addEventListener('click', checkGuess);

Here we are adding an event listener to the guessSubmit button. This is a method that takes two input values (called arguments) — the type of event we are listening out for (in this case click) as a string, and the code we want to run when the event occurs (in this case the checkGuess() function). Note that we don't need to specify the parentheses when writing it inside addEventListener()).
Try saving and refreshing your code now, and your example should work — to a point. The only problem now is that if you guess the correct answer or run out of guesses, the game will break because we've not yet defined the setGameOver() function that is supposed to be run once the game is over. Let's add our missing code now and complete the example functionality.
Finishing the game fun
Let's add that setGameOver() function to the bottom of our code and then walk through it. Add this now, below the rest of your JavaScript:


function setGameOver() {
guessField.disabled = true;
guessSubmit.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Start new game';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', resetGame);
}
  • The first two lines disable the form text input and button by setting their disabled properties to true. This is necessary, because if we didn't, the user could submit more guesses after the game is over, which would mess things up.
  • The next three lines generate a new <button> element, set its text label to 'Start new game', and add it to the bottom of our existing HTML.
  • The final line sets an event listener on our new button so that when it is clicked, a function called resetGame() is run.

Now we need to define this function too! Add the following code, again to the bottom of your JavaScript:


function resetGame() {
guessCount = 1;

const resetParas = document.querySelectorAll('.resultParas p');
for (let i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = ';
}

Number Guessing Program Java

resetButton.parentNode.removeChild(resetButton);

guessField.disabled = false;
guessSubmit.disabled = false;
guessField.value = ';
guessField.focus(); Rise of nations pc game cheat codes.

lastResult.style.backgroundColor = 'white';

Java

randomNumber = Math.floor(Math.random() * 100) + 1;
}

This rather long block of code completely resets everything to how it was at the start of the game, so the player can have another go. It:

  • Puts the guessCount back down to 1.
  • Empties all the text out of the information paragraphs.
  • Removes the reset button from our code.
  • Enables the form elements, and empties and focuses the text field, ready for a new guess to be entered.
  • Removes the background color from the lastResult paragraph.
  • Generates a new random number so that you are not just guessing the same number again!

At this point you should have a fully working (simple) game — congratulations!
All we have left to do now in this article is talk about a few other important code features that you've already seen, although you may have not realized it.
One part of the above code that we need to take a more detailed look at is the for loop. Loops are a very important concept in programming, which allow you to keep running a piece of code over and over again, until a certain condition is met.
To start with, go to your browser developer tools JavaScript console again, and enter the following:


for (let i = 1 ; i < 21 ; i++) { console.log(i) }

What happened? The numbers 1 to 20 were printed out in your console. This is because of the loop. A for loop takes three input values (arguments):

  • A starting value: In this case we are starting a count at 1, but this could be any number you like. You could replace the letter i with any name you like too, but i is used as a convention because it's short and easy to remember.
  • An exit condition: Here we have specified i < 21 — the loop will keep going until i is no longer less than 21. When i reaches 21, the loop will no longer run.
  • An incrementor: We have specified i++, which means 'add 1 to i'. The loop will run once for every value of i, until i reaches a value of 21 (as discussed above). In this case, we are simply printing the value of i out to the console on every iteration using console.log().

Now let's look at the loop in our number guessing game — the following can be found inside the resetGame() function:


let resetParas = document.querySelectorAll('.resultParas p');
for (let i = 0 ; i < resetParas.length ; i++) {
resetParas[i].textContent = ';
}

This code creates a variable containing a list of all the paragraphs inside <div> using the querySelectorAll() method, then it loops through each one, removing the text content of each.
A small discussion
Let's add one more final improvement before we get to this discussion. Add the following line just below the let resetButton; line near the top of your JavaScript, then save your file:

This line uses the focus() method to automatically put the text cursor into the <input> text field as soon as the page loads, meaning that the user can start typing their first guess right away, without having to click the form field first. It's only a small addition, but it improves usability — giving the user a good visual clue as to what they've got to do to play the game.
Let's analyze what's going on here in a bit more detail. In JavaScript, everything is an object. An object is a collection of related functionality stored in a single grouping. You can create your own objects, but that is quite advanced and we won't be covering it until much later in the course. For now, we'll just briefly discuss the built-in objects that your browser contains, which allow you to do lots of useful things.
In this particular case, we first created a guessField constant that stores a reference to the text input form field in our HTML — the following line can be found amongst our declarations near the top of the code:


const guessField = document.querySelector('.guessField');

To get this reference, we used the querySelector() method of the document object. querySelector() takes one piece of information — a CSS selector that selects the element you want a reference to.
Because guessField now contains a reference to an <input> element, it will now have access to a number of properties (basically variables stored inside objects, some of which can't have their values changed) and methods (basically functions stored inside objects). One method available to input elements is focus(), so we can now use this line to focus the text input:

Variables that don't contain references to form elements won't have focus() available to them. For example, the guesses constant contains a reference to a <p> element, and the guessCount variable contains a number.
Playing with browser objects
Let's play with some browser objects a bit.

  • First of all, open up your program in a browser.
  • Next, open your browser developer tools, and make sure the JavaScript console tab is open.
  • Type in guessField and the console will show you that the variable contains an <input> element. You'll also notice that the console autocompletes the names of objects that exist inside the execution environment, including your variables!
  • Now type in the following:

guessField.value = 'Hello';

The value property represents the current value entered into the text field. You'll see that by entering this command, we've changed the text in the text field!

  • Now try typing in guesses and pressing return. The console will show you that the variable contains a <p> element.
  • Now try entering the following line:

The browser will return undefined, because paragraphs don't have the value property.

  • To change the text inside a paragraph, you need the textContent property instead. Try this:

guesses.textContent = 'Where is my paragraph?';

  • Now for some fun stuff. Try entering the below lines, one by one:
  • guesses.style.backgroundColor = 'yellow';
  • guesses.style.fontSize = '200%';
  • guesses.style.padding = '10px';

Every element on a page has a style property, which itself contains an object whose properties contain all the inline CSS styles applied to that element. This allows us to dynamically set new CSS styles on elements using JavaScript.

Conclusion
It is a simple guessing the number game which is fun playing too. It also increases the thinking ability of human to make a right guess.

Related Tutorials

Related Training Courses

Cross-platform Native App Development Using HTML5, CSS3 and JavaScript
Node.JS Coding with Hands-on Training
Developing Web Applications Using AngularJS
Introduction to the WordPress CMS
Introduction to the Joomla CMS
Mastering Drupal in 30 Hours
Intro to Dreamweaver with Website Development Training
Adobe Muse Training Course
PHP and MySQL Coding
Responsive Site Design with Bootstrap
jQuery Programming for Beginners
Object Oriented Programming with UML
SQL Programming and Database Management
Introduction to Python Programming

Introduction

Note: You'll need to know about for loops and if statements for this guessing game, so you'll need to have read all but the last of the beginner tutorials or already know all of these concepts.

In this guessing game, the computer will come up with a random number between 1 and 1000. The player must then continue to guess numbers until the player guesses the correct number. For every guess, the computer will either say 'Too high' or 'Too low', and then ask for another input. At the end of the game, the number is revealed along with the number of guesses it took to get the correct number. Ready to follow along to create this guessing game? All right.

Coding Up the Guessing Game

First, we're going to start by creating a new class, or Java file. Call your new program GuessingGame, keeping the capitalization the same. If you're using Eclipse (and I strongly urge you to!) then make sure to checkmark the box to have it put in your main method for you. You should start out like this:

Ok, we need the computer to generate random numbers. Just add this code inside your main method so you have this:

Don't worry much about how Random works. All you need to know for this guessing game is that the variable numberToGuess holds the integer that the player has to guess. Notice you'll get an error when you try to use Random. This is the same problem that Scanner has. All you have to do is right-click your work area, go to source, and select Organize Imports. This will take care of the problem for you. If you want to just import manually, type in import java.util.Random; at the very top of the page.

Now, we need to stop and figure out exactly what we need our game to do and how we're going to accomplish this goal. It's best to do this planning BEFORE you beign coding, so let's start by listing what the guessing game needs to do, also known as the requirements of the program.

Needs of the guessing game:

  • Creates a random number to guess
  • Keeps track of number of guesses
  • Asks us to guess a number
  • Let user input a number
  • Tells us whether we're guessing too high or too low
  • Keeps playing until we guess the correct number
  • Tells us the correct number and the number of tries
  • This is a small list, but it does say everything we need to do for our guessing game to work. We already took care of the first need, which was to create a random number. So, let's move on to the next requirement, keeping track of the number of guesses.

    To keep track of anything, you need a variable. In this case, since we're keeping track of guesses, a simple integer variable will do. Add an int variable to your code, and start it off at 0, since at the beginning the player has made no guesses.

    So far we have the variable, but it still does not keep track of the number of guesses. At this point it doesn't make sense to make it do so because the user isn't being asked to make any guesses yet.

    Let's have the computer ask us to guess a number. This is pretty simple, and something you've known how to do since the Hello World tutorial if you've been following along.

    Ok, so that requirement is completely done and you can scratch it off your to-do list. Now, we need the player to be able to input the number. This means we're going to need a Scanner.

    I like to define all my variables as high up in the code as possible, and I suggest you try to do the same. It helps you keep track of all the different variables you have and makes sure that you don't accidentally use the same variable twice. So, create a Scanner at right under your variable that keeps track of the number of guesses. You know how to create a Scanner by now, right? :)

    Now that we have a scanner to use, we need to actually have a variable that stores the input from the user. You can create this variable at the top too, but don't make it equal anything yet. Remember how this is done?

    Now with this variable, under where the computer asks for input, have your new variable store the input from the scanner. Remember, the player will be guessing integers, so having the variable be an integer is a must. Also, remember that using nextLine() with Scanner probably isn't the best approach here. Do you remember what to use instead for integers?

    Once you've written the code to accept input, you can scratch that off of your requirements list.

    The computer then needs to tell us if this guess was too high or too low. Notice how in that sentence I used the word if. That's a big clue as to what you need to use to accomplish this. Let's break down the if statement.

    • If the number guessed is higher than the real number, tell us its too high.
    • If the number guessed is smaller than the real number, tell us its too low.
    • If the number guessed is the same as the real number, tell us that we won.

    You could do this in three different if statements, but it's best to use else if in this case to tie them all together. It helps to show that all those if's are related to each other, and that only one of those if's will ever be true at one time (the guessed number can never be too high and too low at the same time, for example).

    This is what your code should look like at this point:

    Great, we can cross of another requirement off of our list. This is what we have left to do:

    • Keeps track of number of guesses (remember we only finished part of it)
    • Keeps playing until we guess the correct number
    • Tells us the correct number and the number of tries

    Let's tackle the first item on that list and get rid of it once and for all. When should we track the number of guesses? Right after the player guesses the number of course! Just add one to the variable we created to do this after the player guesses a number. That's all there is to it!

    Okay, so if we were to run our guessing game right now, the program would go one time, and then stop. This is because we need it to keep going until the user wins. We will have to think about this a little bit before we code it.

    First of all, what ways do we know to make Java do something over and over again? In the tutorials we went over two ways, the for loop and the while loop. If you remember the difference, then you know that the for loop loops for a certain number of times. Unfortunately the number of times this program could loop depends on the player! So, a for loop is probably not the best way to handle this.

    A while loop is the perfect choice. It keeps going until a condition is no longer true. So, while the player hasn't won yet, keep going. But how do we keep track of whether or not the player has won?

    Simple. We use a boolean variable. We can create a boolean variable called win near the top of our code with all the other variables. If we set win to false, then it means the player hasn't won yet. When win is true, then the player won the game.

    The last thing we need to figure out is which code to put inside of this while loop. I recommend everything starting from the computer asking the player to guess a number all the way down to the if statements.

    See how inside the while loop parenthesis the condition is when win is equal to false? This means it will continue to loop until something sets the win variable to true.

    But what will set the win variable to true? The third part of the if statement seems like a good choice. You know, the part that asks if the player guessed the correct number. Here is what this looks like:

    Phew, so now we've gotten rid of all the requirements except one. We need the game statistics when the game is over. Ok, after your while loop, we can add the code in. It should just be a series of printlns that tell us everything we need to know, such as number of guesses made.

    Your guessing game program is now complete!

    Go ahead and play it. I wouldn't try guessing letters or anything like that, as your program will crash. However, the game does work, so enjoy or show it off!

    Note: By the way, to make the guessing game harder or easier, simply change the number inside of the parenthesis of the Random variable we created. You can change it from 1000 to 10 so it creates a number from 1 to 10, or you can make the number larger. Have fun!

    **Editor's Note: The game actually picks a number between 0 and 999, not 1 and 1000. You can add one to the numberToGuess variable to fix that issue.

    If you have any questions, comments, or concerns, feel free to contact us.