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