gpt4 book ai didi

java - Hi-Lo 猜谜游戏 - 限制用户输入的尝试次数和重玩逻辑

转载 作者:行者123 更新时间:2023-12-01 20:04:45 27 4
gpt4 key购买 nike

我是 Java 编程新手,正在学习大学类(class),其中的作业是创建一个高/低猜谜游戏。游戏为用户提供最多 5 次尝试输入 1 到 100(含)之间的数字的机会。程序必须提供答案是否太低、太高或正确的逻辑支持。该程序必须提供在获胜或 5 次失败尝试后再次玩的选项。

我已经重新创建了这个程序大约 10 次:(。我无法让他的逻辑按照上面的说明进行操作。我无法在 5 次尝试后停止尝试...并且我无法让程序执行新游戏.

非常感谢任何帮助。我花了无数的时间编写和重写这段代码,得到了许多不同的结果 - 但不是预期的结果。

这是我第一次发帖,如果发帖格式不正确,我深表歉意。

我浏览过的论坛和示例比我愿意承认的要多,而且我审查和尝试实现的代码都没有给我带来将用户输入每次尝试限制为 5 次以及能够多次重玩的结果.

这是我的代码:

public class HiLoGuessingGame {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//Initialize scanner and random number gennerator
Scanner input = new Scanner(System.in);
Random generator = new Random();

//State the rules of the game
System.out.println("The Hi-Lo Guessing Game. Guess a number between 1-100");
System.out.println("You have 5 attempts!");

/* define the variable Guess (user iput)
define the variable Answer (random generator)
define the variable Counter (track number of tries and limit to 5)
define the variable PlayAgain (Y/N question)*/
int guess = 0;
int answer = generator.nextInt(100)+1;
int counter = 1;
String playAgain;
boolean gameOver = false;

//Ask the Hi-Lo question - pick number 1-100 (inclusive)
//Provide feedback answer too high, too low or you win!
//Limit number of tries in the game to 5

while (guess != answer) {
System.out.print("Enter your guess: ");
guess = input.nextInt();
counter++;

if (guess < answer) {
System.out.println("Your guess " + guess + " is too low. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess > answer) {
System.out.println("Your guess " + guess + " is too high. Try again");
System.out.println("This is attempt: " + counter);
} else if (guess == answer) {
System.out.println("Your guess " + guess + " is correct! You win!");
System.out.println();
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}

}
if (counter ==6) {
System.out.println("Sorry, you've reached your max atttempts.");
System.out.println("Would you like to play again (Y/N)?");
playAgain = input.next();
}

// Play again logic
boolean isValid;
do {
System.out.print("Would you like to play again (Y/N)?");
playAgain = input.next().toUpperCase();
isValid = playAgain.equals("Y") || playAgain.equals("N");
playAgain = input.next();
counter = 1;
if ( !isValid ) {
System.out.println("Error, please enter Y or N");
System.out.println();
}
} while (!isValid);
}
}

最佳答案

您可以向 while 循环添加额外的条件:

while (guess != answer && counter < 5) {
// ...
}

或者,您可以在得到正确答案时打破循环:

 while (counter < 5) {
// ...
if (answer == guess){
// ...
break;
}
}

关于java - Hi-Lo 猜谜游戏 - 限制用户输入的尝试次数和重玩逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58990648/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com