mercredi 30 septembre 2015

Java : Nesting an if/else statement inside a while loop

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;

        }
    }
}

Aucun commentaire:

Enregistrer un commentaire