2

this is my first question in StackOverflow, so I hope that you will forgive me for the many possible error I'm going to make in setting this post.... My problem is the following : this code should generate a random number, display it to the user(in order to help me guess it whitout making too many attempts... this should be only an exercize), ask the user to guess a number between 0 and 50, check if the input is an integer or not and, If the user guesses the right number, print "Yes, the number is.." . BUT, if the user digits a letter or whatever which is not a number, the if/else loop goes crazy and the program starts printing "Choose a number between 0 and 50: Please insert a number between 0 and 50, not a letter" whitout stopping... Can anywone help me please?

package methods;

import java.util.Scanner;

public class Methods {

    static int randomNumber;
    static Scanner userInput = new Scanner(System.in);

    public static void main(String[] args) {

        System.out.println(getRandomNum());

        int guessResult = 1;
        int randomGuess = 0;

        while (guessResult != -1) {
            System.out.print("Choose a number between 0 and 50: ");

            if (userInput.hasNextInt()) {
                randomGuess = userInput.nextInt();
                guessResult = checkGuess(randomGuess);
            } else {

                System.out.println("Please insert  a number, not  a letter");
            }

        }

        System.out.println("Yes, the number is " + randomGuess);
    }

    public static int getRandomNum() {

        randomNumber = (int) (Math.random() * 51);
        return randomNumber;

    }

    public static int checkGuess(int guess) {

        if (guess == randomNumber) {

            return -1;
        } else {

            return guess;

        }
    }
}
Shriram
  • 4,343
  • 8
  • 37
  • 64
  • 1
    @ChicagoRedSox It wouldn't help the algorithm to modify guessResult in the else branch. – laune Sep 30 '15 at 16:40
  • @ChicagoRedSox that would not be the way to solve his issue. He wants to continue asking for input, after prompting with an error. He needs to read String not read Integer – James Wierzba Sep 30 '15 at 16:54

1 Answers1

1

You are allowing the user to enter a letter (with the intention giving an error message, but you only call scanner.nextInt)

You should read the input as a string, and then parse it.

    String input = null;
    while (guessResult != -1) {
        System.out.print("Choose a number between 0 and 50: ");

        input = sc.next();
        try
        {
            randomGuess = Integer.parseInt(input);
            checkGuess(randomGuess);
        } catch(NumberFormatException ex)
        {
            System.out.println("Please insert  a number, not  a letter");
        }

    }
James Wierzba
  • 16,176
  • 14
  • 79
  • 120