Last Updated:

Practicum: writing together a simple game in Java 

Today I decided to share with you the code of a small console quiz in the programming language Java. The quiz is called "guess the number." Of course, this is more of an educational example, although, in its image and likeness, you can create something more serious. But today we will not set such tasks for ourselves.

The game, of course, has flaws. First of all, this is the lack of a visual interface . Also, you can not insert letters and spaces in the input field - the code will "throw" an exception. But if you want, this is not difficult to fix, which, in general, will be a good training for you in the development of simple Java constructs. Of course, the article is not suitable for those who do not know Java programming at all. But the one who takes even the first steps in it will understand everything.

So, what do we need? First of all, of course, the IDE is needed to work. I used Eclipse, although in Net Beance my code worked and edited quite correctly.

Next, we need to ensure that the necessary library classes are imported. They have everything we need to process our code.

import java.io.*;

import static java.lang.System.out;

Open the IDE and create a new project, in it - a new class with any name and necessarily with the main method, in the body of which our program is located. Every Java program must have a static main method—it returns nothing, only points to the code to run.

public static void main(String[] args) 

throws NumberFormatException, IOException, 

IndexOutOfBoundsException{

TODO Auto-generated method stub

Then we create two integer variables ? i and l. One (i) is initialized. This will be a counter variable. The fact is that we decided to give the user exactly 5 attempts to guess the number. After each wrong step, a "unit" will be added to our variable i. And if the user does not guess the number for the fifth time, we will tell him that he lost.

int i = 0;

int l;

Now create an array (an array is a set of any values: numbers, symbols, strings, variables). It is always numbered from zero to the last element. We will set the array manually and write down all the user's steps there. At the same time, we must foresee all his mistakes. Well, almost all of them.

String[]notNotice = {

"\nfirst time", "\nth time", "\nthretii raz", "\nchetvesty", "It was"

+ "last attempt, you lost", "You entered too many, you made a mistake",

"You entered too small a number, you made a mistake", "You entered the correct number and won!", "Enter"

+ "number", "Guess the number up to 100 and enter here", "You lost", "You entered negative"

+ "number, Enter number", "You entered a negative number, Enter a number"};

Now we create a field for the user to enter numbers. To do this, we'll need a buffered class, BufferedReader. Or rather, a copy of it. Where it says (notNotice[9]), we will see the phrase "Guess the number up to 100 and enter here" substituted from the array. An instance of the StringBuilder class and its .append method will allow us to reduce the load in the program. The fact is that Java is designed in such a way that it turns each line into an array, and if we begin to combine them all with a simple "+" operator, the machine will perform many unnecessary operations.

  BufferedReader reader = new BufferedReader

(new InputStreamReader(System.in));

StringBuilder lr = new StringBuilder();

    lr.append(notNotice[9]);

    lr.append(" ");

lr.append("\nIn You only have 5 attempts!");

Output a message by using the println method.

       out.println(lr.toString());

The Integer.parseInt method will allow us to read numbers from a string (string and numbers for Java are different types of data and without specifying exactly what to read, the development environment  will give an error).

                    int s = Integer.parseInt(reader.readLine());

                                   Random r = new Random();

The next step is to output a random number. We'll do it using the .nextInt method. And although, objectively, this method still does not operate with random categories (there is nothing random in the computer at all), it is still difficult to "bite" it.

         int x = r.nextInt(100)+1;

                        l=x;    

From here begins the most "favorite" part of the work of programmers - setting conditions and cycles for the computer. That is, an explanation of what should he consider? For example, this while loop with a number of if conditions explains that until the number of incorrect input attempts exceeds five, the user needs to explain that he entered either too large or too small a number. Here he is forbidden to enter negative numbers and, in fact, zero. For him, the appropriate phrases are displayed and please try again.

                        while(i<=5) {      

If the user wins, a corresponding message is displayed to him and the game ends (break;).

                      if(s==l)

                      {

                    out.println(notNotice[7]);

                    break;

                      }               

Zero cannot be entered. An erroneous attempt will be counted.

                      if(s==0){

                           StringBuilder mr = new StringBuilder();

                          mr.append(notNotice[9]);

                          mr.append(notNotice[11]);

                             out.println(mr.toString());

                             int k = Integer.parseInt(reader.readLine());

                       i++;

                       s=k;

                                 }                                            

Warning that too many numbers have been entered.

                         if(s>x){

                          StringBuilder mr = new StringBuilder();

                        mr.append(notNotice[5]);

                        mr.append(" ");

                        mr.append(notNotice[i]);

                        mr.append(" ");

                        mr.append(notNotice[8]);

                       out.println(mr.toString());

                           int z = Integer.parseInt(reader.readLine());

                     i++;

                     s=z;

                         }

Warning that you enter too small a number.

                     if(s<x&&s>0){

                      StringBuilder mr = new StringBuilder();

                   mr.append(notNotice[6]);

                   mr.append(" ");

                   mr.append(notNotice[i]);

                   mr.append(" ");

                   mr.append(notNotice[8]);

                  out.println(mr.toString());

                   int m = Integer.parseInt(reader.readLine());

                     i++;

                     s=m;

                     }          

Negative numbers cannot be entered. Again the attempt failed.                                                

                     if(s<0){

                      out.println(notNotice[12]);

                      int v = Integer.parseInt(reader.readLine());

                      s=v;

                      i++;

                     }

After the fifth incorrect input, a message about the loss is displayed and the game stops. Who can tell me why the number "4" and not "5" is here? Well well?

Correct! We started counting from scratch!

                   if (i==4 && s!=l){  

                         StringBuilder mr = new StringBuilder();                          

                        mr.append(notNotice[4]);

                     mr.append("\n");

                              out.println(mr.toString());

                              break;

                                         }

                     }

That's it. It remains to add that having disassembled the code described by me (and this is not difficult), you can already work a little with Java. Good luck!