lundi 2 avril 2018

Random two-digit number guessing game in Java

I'm working on a "game" for the user to guess a random two-digit number, and this is my "robust" version so far:

import static java.lang.System.*;
import java.util.*;

public class RandomNumberGuessing {

public static Scanner scan = new Scanner(in);

public static void main(String args[]){
    Random generator = new Random ();
    int Low = 10;
    int High = 99;
    int answer = generator.nextInt (High - Low) + Low;
    int answerFirstDigit = Integer.parseInt(String.valueOf(answer).substring(0,1));
    int answerSecondDigit = Integer.parseInt(String.valueOf(answer).substring(1,2));
    int count = 0;
    out.println ("Welcome to the two digit number guessing game!");
    out.println ("We have randomly chosen a two-digit number");
    out.println ("And you have to guess it after 5 tries!");
    out.println ("Guess the number: ");
    while (!scan.hasNextInt ()) {
        scan.next ();
        out.println ("You have to input a valid two-digit integer!");
    }
    int guess = scan.nextInt ();
    while (guess != answer && count < 4){
        count ++;
        out.println("Wrong number! You have " + (5 - count) + " tries left:");
        if (Integer.parseInt(String.valueOf(guess).substring(0,1)) == answerFirstDigit){
            out.println("But you got the first digit correctly!");
        } else if (Integer.parseInt(String.valueOf(guess).substring(1,2)) == answerSecondDigit){
            out.println("But you got the second digit correctly!");
        } else if (Integer.parseInt(String.valueOf(guess).substring(1,2)) == answerSecondDigit || Integer.parseInt(String.valueOf(guess).substring(0,1)) == answerSecondDigit){
            out.println("One or two digits are correct but in the wrong place!");
        }
        while (!scan.hasNextInt ()) {
            scan.next ();
            out.println ("You have to input a valid two-digit integer!");
        }
        guess = scan.nextInt ();
    }
    if (guess == answer){
        out.println("Congratulations! The number was " + answer + "!");
    } else{
        out.println("The number was " + answer + ". Better luck next time!");
    }
}

}

But I'm having a problem with forcing the user to input a two-digit number only. I tried using:

while(guess < 10 || guess > 99){
   scan.next();
   out.println("Invalid number!");
   guess = scan.nextInt();
}

I added that after the while loop to make sure the user entered an integer, and when I enter a 3 or 4-digit number in the console (I run the code on IntelliJ IDEA), it just seems to hang with no response. It doesn't even print out "Invalid number!" and just hangs. Do I have to rewrite the code using methods or are there any other things I can add to the existing code to make sure the user enters a TWO-DIGIT INTEGER? Thanks in advance




Aucun commentaire:

Enregistrer un commentaire