Guess the Number

In this article we will be finishing up our series on the Guessing game. In the past we developed a guessing game with Go as well as with Rust. This post will be using Java. If you have read the other two posts please feel free to skip this section and move on to the next. In this series of posts I wanted to choose an application that could be used to show the similarities of three languages as well as their differences. I chose Go and Rust because those are the langauges that I am currently using in my spare time. The third language I chose was Java as it is a good all around language to learn and know. I also feel that seeing the same app done in an OOP(Object Oriented Programming) way will help you see how you can do that in Go and Rust. I have also been using Java a bit more these days and wanted to do something fun.

Creating a Dev Environment

Now I am sure that most of you reading this post are already developers and already have your editor or IDE of choice. Nothing wrong with that at all. However if this is your first time getting started with programming, first off I want to say thank you for stopping by my blog page, and second I will be covering a few different editors/IDEs that you can choose from.

VS Code

This is the editor I feel a lot of people choose. It’s free and it has support for just about every language you can think of. If this is your first time ever programming anything I recommend VS Code as it is very simple to work with and runs on all major OS’s. You can download it here. Once you have it installed I recommend getting the Java extension. It will install quite a bit of things and not all of them are necessary right now for this game but over time you might need them as you become more familiar with Java.

IntelliJ IDEA

This is a great IDE for creating Java based applications. It has plenty of support for Java. There is two different versions of the IDE, the Community Edition and Ultimate Editions. The Community Edtion will be all you need for this post and more than likely your Java learning journey. However if you find yourself needing more from your IDE then you can always look into the Ultimate Edition. Download the Community Edition if you want to give it a try.

Eclipse

This is another really great editor for using and learning Java if you are a beginner. If you only plan on using Java or possibly using web development technologies then this IDE is perfect. Download Eclispe

I use IntelliJ or VS Code as they are the easiest to get up and running with. With Eclipse there is a little bit more setup than the others but it is entirely up to you as to which one you choose.

Note If you plan on doing any type of Android development then you will want to download and install Android Studio.

Installing Java

Ok now that we have our editor or IDE of choice downloaded and installed let’s actually get Java installed on our machine. We can download Java. Just follow the installation wizard and you will have Java installed in no time. You can verify you have it installed by opening up your terminal and typing:

$ jshell
| Welcome to JShell -- Version 19.0.1
| For an introduction type: /help intro
jshell>

You should be able to see the welcome message and your prompt will change from a $ to jshell>. In order to exit type /exit. With this confirmed we are able to start our project.

Sarting Our Project VS Code

We can now create our project. We will be covering two options on how you can create a project. The first option is for those using VS Code. Let’s get started.

$ cd Desktop
$ mkdir javaProjects
$ cd javaProjects
$ mkdir guessingGame
$ cd guessingGame
$ code .

We just set up our directories and opened our project up in VS Code. We are now ready to start.

Starting Our Project Using IntelliJ

Open up IntelliJ and follow these steps:

  1. New Project
  2. On the left hand side select New Project
  3. Enter a Name for the project in the middle
  4. Select your location to store(save) the project Desktop/javaProjects
  5. Select Java for the Language
  6. IntelliJ for the build system
  7. JDK should be set to 19
  8. Click Create

IntelliJ will create a project and open it in the editor. You should now be ready to start our project.

Creating Our Game Class

We are now ready to write our game. In your project right click on the directory of your app and choose new file name it Game.java. NOTE: In IntelliJ you don’t have to put the .java part. VS Code you do. This will create our file and open it up so we can start writing our code. Let’s get started.

import java.util.Scanner;

public class Game {
    // Our function that starts the game
    public static void guessTheNumber() {
        // Scan for user input
        Scanner s = new Scanner(System.in);

        // Generate random number
        int number = 1 + (int)(100 * Math.random());

       // Set guess amount
        int GuessAmount = 10;

        System.out.print("I'm thinking of a number between 1 and 100. Can you guess it?");

        int guess = s.nextInt();

        System.out.println(guess);
    }
}

We are creating our class. Here we import the Scanner class so that we can use it to scan for user input. Inside our class we use the Scanner class to instantiate a new scanner which we then set to s. Then we create a new random number which is our number variable. We set the amount of guesses next. Then we set our guess variable to the scanner which takes in the next integer value input by the player. We then print out to the terminal our message for the user to guess the random number. And finally we print the player’s guess. Right now this is just to make sure that our project is up and running and we are getting user input.

Updating Our Class

Now that we have established that our Game class is working by setting up our scanner object, creating a random number between 1 - 100, and taking player input and then printing that out, we can modify our code to have a game loop and finish out the game.

public class Game {
    ...
    int guessAmount = 10;

    int i, guess;

    for(i = 0; i < guessAmount; i++) {
        System.out.println("Guess the number: ");

        // Take input
        guess = s.nextInt();

        if (number == guess) {
            System.out.println("You win!");
            break;
        } else if (number > guess && i != guessAmount - 1) {
            System.out.println("Too high!");
        } else if (number < guess && i != guessAmount - 1) {
            System.out.println("Too low!");
        }
    }

    if (i == guessAmount) {
        System.out.println("You have run out of guesses");

        Systtem.out.println("The number was " + number);
    }
}

public static void main(String arg[]) {
    guessTheNumber();
}

We can now test our game by running it. Play it a few times and verify that the functionality is all working. Really awesome right? We now have a pretty cool game where we can try to guess a number within 10 attempts. You can of course change the amount of guess to any number you want as well as the numbers used 1 - 100 is our current choice but you could of course make it be 1000 instead. So cool.