简体   繁体   中英

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

To check that the user enters just two digit numbers, i would use two methods to verify that. Things to check:

  1. User must enter something, ie do not accept null or empty
  2. Everything user enters must be exactly two characters long
  3. When the characters are two, they have to all be digits

In your program you can do these
1. Get input as string
2. Call validString
3. If valid, then convert to integer
4. Check that number is between range (if the user entered 01, this evaluates to true). Integer.ParseInt could catch this but good to check anyway

Complete program should be something like this

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

public class RandomNumberGuessing {

public static Scanner scan = new Scanner(in);

public static void main(String args[]) {
    final int tries = 5; // max number of tries
    Random generator = new Random();
    int Low = 10;
    int High = 99;
    int answer = generator.nextInt(High - Low) + Low;

    int firstDigit = getFirst(answer);
    int secondDigit = getSecond(answer);

    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 " + tries + " tries!");

    int guess = 0; // number guessed
    int count = 0; // number of failed guesses

    do {
        out.println("Guess the number: ");

        String guessString = scan.nextLine(); // just read everything
                                              // entered

        if (validString(guessString)) {
            guess = Integer.parseInt(guessString);
            if (guess >= Low && guess <= High) { // check range and only
                                                 // process valid range
                count++;
                if (count == tries) {
                    out.print("Max guess reached.\nThe values were ");
                    out.println(firstDigit + " and " + secondDigit);
                    break;
                }
                out.println("You guessed " + guess);

                // get the first and second digits
                int first = getFirst(guess);
                int second = getSecond(guess);

                // compare them and process
                if (guess == answer) {
                    out.println("Congratulations. You made the right guess after "
                                    + count + " tries");
                } else if (first == firstDigit) {
                    out.println("Guessed the first number rightly");

                } else if (second == secondDigit) {
                    out.println("Guessed the second number rightly");
                } else {
                    out.print("No matching guess. You have ");
                    out.println((tries - count) + " guesses left");
                }
            } else {
                out.println("Out of range!");
            }

        } else {
            out.println("Bad Value.");

        }

    } while (guess != answer && count < tries);

}

// Validate an input Checks for length [2 characters] and that everything is
// a digit
private static boolean validString(final String guess) {
    if (guess != null && !guess.isEmpty()) { // if not null and not empty

        if (guess.length() == 2 && isAllDigits(guess)) { // length and digit
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

// Verify that all characters in a string are numbers
private static boolean isAllDigits(final String input) {
    for (char c : input.toCharArray()) {
        if (!Character.isDigit(c))
            return false;
    }
    return true;
}

// get the first digit
private static int getFirst(final int value) {
    return Integer.parseInt(String.valueOf(value).substring(0, 1));
  }

// Get the second digit
private static int getSecond(final int value) {
    return Integer.parseInt(String.valueOf(value).substring(0, 1));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM