【发布时间】:2017-07-02 06:39:04
【问题描述】:
我在以下代码中的目标是不断猜测,直到用户猜对或退出。要退出,我可以轻松地跳出我的循环,但是当我尝试继续我的循环时,它不能正常工作。首先它需要多个输入,然后也完全重新生成我的号码,而我想要做的是不断猜测(询问用户)相同的随机数。 以下是我的代码:
public class Test {
public static void main(String[] args) {
int count, randNum, guess;
count = 0;
Scanner scan = new Scanner(System.in);
while (true) {
Random rand = new Random();
randNum = rand.nextInt(100) + 1;
System.out.println("Guess a number b/w 1 and 100");
guess = scan.nextInt();
count += 1;
if (guess == randNum) {
System.out.println("Correct guess.");
System.out.println("It took " + count + " tries to guess the right number");
System.out.println("Would you like to play again? ");
System.out.println("Press any letter to play again or q to quit: ");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else{
continue;
}
}
if (guess > randNum) {
System.out.println("Your guess is bigger than actual number. Would you like to try again?");
System.out.println("Press q to quit or any other letter to try again");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else {
continue;
}
}
else if (guess < randNum) {
System.out.println("Your guess is smaller than actual number. Would you like to try again?");
System.out.println("Press q to quit or any other letter to try again");
if (scan.next().charAt(0) == 'q' || scan.next().charAt(0) == 'Q') {
break;
}
else {
continue;
}
}
}
}
}
【问题讨论】:
-
谈论一个移动的目标 - randNum 正在循环的每次迭代中重新设置
-
您需要将游戏和尝试分成外/内循环。
标签: java if-statement while-loop conditional