SenorWaffels
SenorWaffels

Reputation: 53

Guessing random number

I am in the process of learning Java, at least i am trying. Now i made an app where you need to guess the random number generated with math.random.

Here is the code:

import java.util.Scanner;

public class var {
    public static void main(String[] args) {

        Scanner keyboard = new Scanner(System.in);
        //var definitie
        int player;
        int rnummer;

        rnummer = (int) (Math.random() * 50 + 1);

        System.out.println("Raad het nummer!");
        player = keyboard.nextInt();
        System.out.println(rnummer);

        //goed geraden check
        if (player == rnummer) {
            System.out.println("Helaas, dat is niet juist.");
            player = keyboard.nextInt();
        }
        System.out.println("Goed geraden!");
    }
}

Now there is a problem where every time you guess it is right, you cannot guess wrong. I cannot figure out the problem.. it must be very simple.

Upvotes: 0

Views: 313

Answers (2)

AxelH
AxelH

Reputation: 14572

You need to understand that statement :

if (player == rnummer) 
{
     System.out.println("Helaas, dat is niet juist.");
     player = keyboard.nextInt();
}

This means :

if player is equals to rnummer
then 
     print "Helaas, dat is niet juist."
     ask a value and store it in player
and read the next line

But what you want is

if player is NOT equals to rnummer
then
     print "Helaas, dat is niet juist."
     ask a value and store it in player
check again the condition

This is what we call a loop. This is similar than an if but will only exit the statement when the condition is false.

while(player != rnummer) 
{
    System.out.println("Helaas, dat is niet juist.");
    player = keyboard.nextInt();
}

An if only execute the block statement once if the condition is true.

A while will execute the block until the condition is false.

NOTE : Since a loop only end when the condition is false (not completly true, some keywords can exit those, but this is an other subject), you can end up with an infinite loop, that means the condition will NEVER be false.

while(true){
    //Statement
}
// Unreachable code

Upvotes: 6

SimoV8
SimoV8

Reputation: 1402

You simply need to substitute the if statement with a while loop:

while (player != rnummer) {
    System.out.println("Helaas, dat is niet juist.");
    player = keyboard.nextInt();
}

that in natual language can be tranlated in "While your guess is different from the random number, keep trying". If you use only an if, the code inside the {} brackets will be executed only if the condition it's true, but after that the program will continue with the next instruction that is System.out.println("Goed geraden!"); in your code.

Upvotes: 2

Related Questions