Ian Stacy
Ian Stacy

Reputation: 3

Having the user guess a random number and loop until they get it right

I've been trying to figure this out for hours but I can't for some reason my output just shows "Sorry that number is too high" and "Sorry that number is too low" at the same time without looping or using a single answer.

import java.util.*;

public class RandomNumbers {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        Random numGen = new Random();
        int RanNum = numGen.nextInt(20) + 1; 
        System.out.println("Guess what number im thinking of");
        int num ;
        num = keyboard.nextInt();
        if (num == RanNum)
            System.out.println("Good Job");
        else if  (num > RanNum)
            System.out.println("Sorry that number is too high");
        else if (num < RanNum);
        System.out.println("Sorry that number is too low");

    }
}

Upvotes: 0

Views: 229

Answers (3)

Tim Hunter
Tim Hunter

Reputation: 242

To keep prompting the user use a while loop to check whether they guessed correct or not. I would also recommend adding another input check for exiting without getting it correct. Brief example:

boolean incorrect = true;
while(incorrect) {

  //Code to prompt for input

  if(userIsCorrect || input == -1){
    incorrect = false;
    //Program will exit loop when this is set to false
  }
}

Upvotes: 0

user10419911
user10419911

Reputation:

you misplaced a semicolon at the end of your third if. You should still get the Good Job message though.

public static void main(String[] args) 
{
    Scanner keyboard = new Scanner(System.in);
    Random numGen = new Random();
    int RanNum = numGen.nextInt(1) + 1; 
    System.out.println("Guess what number im thinking of");
    int num ;
    num = keyboard.nextInt();
    if (num == RanNum)
        System.out.println("Good Job");
    else if  (num > RanNum)
        System.out.println("Sorry that number is too high");
    else if (num < RanNum)
        System.out.println("Sorry that number is too low");

}

edit: sorry, too late :)

Upvotes: 0

user1944429
user1944429

Reputation:

Semicolon after else if (num < RanNum) is your problem

Upvotes: 3

Related Questions