【问题标题】:Random two-digit number guessing game in JavaJava中的随机两位数猜谜游戏
【发布时间】:2018-09-11 17:20:24
【问题描述】:

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

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 上运行代码),它似乎只是挂起,没有回复。它甚至不会打印出“无效号码!”只是挂起。我是否必须使用方法重写代码,或者是否可以在现有代码中添加任何其他内容以确保用户输入两位数整数?提前致谢

【问题讨论】:

    标签: java random integer


    【解决方案1】:

    要检查用户是否只输入了两位数字,我将使用两种方法来验证这一点。 检查事项:

    1. 用户必须输入内容,即不接受 null 或空
    2. 用户输入的所有内容都必须正好是两个字符
    3. 当字符为两个时,它们都必须是数字

    在您的程序中,您可以执行这些操作
    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));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 2019-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多