Java中的随机两位数猜数游戏

时间:2018-04-02 13:22:37

标签: java random integer

我正在开发一个“游戏”,供用户猜测一个随机的两位数字,这是我迄今为止的“强大”版本:

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

}

但我在强迫用户输入两位数字时遇到问题。我尝试使用:

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

我添加了while循环以确保用户输入一个整数,当我在控制台中输入一个3位或4位数字时(我在IntelliJ IDEA上运行代码),它似乎挂起了没有响应。它甚至没有打印出“无效的号码!”然后挂起我是否必须使用方法重写代码,还是我可以添加到现有代码以确保用户输入TWO-DIGIT INTEGER?提前致谢

1 个答案:

答案 0 :(得分:0)

要检查用户只输入两位数字,我会使用两种方法来验证。 要检查的事项:

     
  1. 用户必须输入内容,即不接受空或空
  2.  
  3. 用户输入的所有内容必须正好两个字符
  4.  
  5. 当字符为2时,它们必须全部为数字
  6. 在您的计划中,您可以执行这些操作  1.输入字符串
     2.调用validString
     3.如果有效,则转换为整数
     4.检查该数字是否在范围之间(如果用户输入01,则评估为真)。 Integer.ParseInt可以抓住这个,但无论如何都要检查

    完整的程序应该是这样的

    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));
        }
    }
    
相关问题