我似乎无法让我的程序询问用户是否想再玩一次。该程序在询问是否愿意继续时结束。我添加了一个休息时间,因为在程序不断循环正确的答案和尝试次数之前。
import java.util.Random;
import java.util.Scanner;
public class GuessTheNumber {
public static void main(String[] args) {
boolean play = true;
Scanner input = new Scanner(System.in);
Random Number = new Random();
int GuessNumber = 1+ Number.nextInt(1000);
int guess = 0;
int Tries = 0;
while(play) {
while(guess != GuessNumber) {
System.out.println("Please Enter a number between 1 and 1000:");
guess = input.nextInt();
Tries++;
if(guess == GuessNumber) {
System.out.println("You Win!");
break;
}
else if(guess < GuessNumber) {
System.out.println("Guess is too low");
}
else if(guess > GuessNumber) {
System.out.println("Guess is too high");
}
}
System.out.printf("Number was: %d",GuessNumber);
System.out.println("");
System.out.printf("Number of tries was: %d ",Tries);
System.out.println("");
System.out.println("Would you like to play again?(Yes/No)");
String playagain = input.nextLine();
if("Yes".equals(playagain))
play = true;
else
play = false;
}
}
}
答案 0 :(得分:0)
您的计划的一些内容。
正如评论所指出的,您需要在使用nextInt()
后刷新换行符。
但是,在用户声明他们想要再次播放之后,你还必须设置猜测值和尝试计数回到0 - 否则程序将继续“你赢了!”环。
我建议将变量声明移动到外部循环:
while(play) {
int guess = 0;
int guessNumber = 1 + Number.nextInt(1000);
int tries = 0;
...
}