我在java中创建了一个猜谜游戏。它非常简单:计算机选择一个随机数,用户可以选择是否需要5,10或20个机会来猜测这个数字。在每次猜测之后,程序将告诉他们他们的猜测是高于还是低于幻数。如果他们猜出这个数字,他们会收到一条祝贺信息,然后他们会问他们是否想再次参加比赛。如果他们没有猜到这个号码,他们也会收到一条消息,并询问他们是否想再玩一次。有一件事我想添加到我的代码中,我似乎无法弄明白...... 当用户猜出幻数时我想在祝贺信息之后做这样的事情:
恭喜,鲍勃!你猜到了6个猜测中的神奇数字。
你没有使用这些猜测:
7
8
9
10
我尝试了这个,我很快意识到没有任何意义,但是从这里开始我就被卡住了。
System.out.println("You did not use these guesses: "+ (i-numberOfGuesses));
我应该怎么做呢?我宁愿不使用数组。
import java.util.Random;
import java.util.Scanner;
public class NewClass
{
public static void main(String [] args)
{
final String SENTINEL = "no";
int guess;
String playAgain;
int numberOfGuesses;
Scanner scan = new Scanner( System.in );
System.out.print( " Enter your name: ");
String name = scan.next();
System.out.print(" Would you like to try to guess a number? (Yes or No):");
String answer = scan.next();
while(!answer.equals(SENTINEL)){
if (answer.equals("yes"))
System.out.print("How many guesses would you like? (5, 10, 20): ");
do {
numberOfGuesses = scan.nextInt();
if (numberOfGuesses == 5 || numberOfGuesses == 10 || numberOfGuesses == 20 )
break;
System.out.print("How many guesses would you like? (5,10,20): ");
} while (true);
Random random = new Random();
int randomNumber = random.nextInt(100) + 1;
{
for(int i = 1; i <= numberOfGuesses ; i++){
System.out.print("Enter guess #"+i+": ");
guess = scan.nextInt();
if (guess > randomNumber && guess <= 100)
System.out.println("Your guess, "+guess+", is greater than the magic number.");
else if (guess < randomNumber && guess > 0)
System.out.println("Your guess, "+guess+", is less than the magic number.");
else if (guess == randomNumber){
System.out.println("Congratulations, "+name+"! You guessed the magic "
+ "number in "+i+" guesses.");
System.out.println("You did not use these guesses: "+ (i-numberOfGuesses));
break;
}
else
i--;
if (i == numberOfGuesses)
System.out.println("Sorry, " + name+", you did not guess the magic "
+ "number, " + randomNumber + ", in "+ numberOfGuesses + " tries.");
}
System.out.print("Would you like to try to guess a number? (Yes or No):");
answer = scan.next();
}
}}}
答案 0 :(得分:0)
我认为你应该用这个循环替换你提出的(但是不正确的)代码行:
if (i != numberOfGuesses) {
System.out.println("You did not use these guesses: ");
for (int j = i + 1; j <= numberOfGuesses; j++) {
System.out.println(j);
}
}
另外,你有一个错误:如果你在开头回答是,一切都很好,你玩游戏。但是如果您回答是(如问题中所提出的)或任何其他文本,它会等待另一个输入,当您输入内容并按回车键时,它会继续游戏。因此,如果您输入&#34;否&#34;,请按Enter键,输入1,按Enter键仍然会播放。