gpt4 book ai didi

java - 简单的猜谜游戏。 "Your first guess is...."

转载 作者:太空宇宙 更新时间:2023-11-04 13:01:15 25 4
gpt4 key购买 nike

我正在通过三次尝试创建这个简单的猜测游戏,但我需要添加代码的帮助,以便它可以显示“第一次猜测”,后跟用户输入的整数,“第二次猜测”等......我目前只有“输入你的猜测”,这是第一次尝试。我需要做什么?我对如何去做这件事感到困惑。如果问题令人困惑,抱歉。

import java.util.Scanner;

public class guess {

public static void main(String[] args) {

int randomN = (int) (Math.random() * 10) + 1;

Scanner input = new Scanner(System.in);
int guess;
System.out.println("Enter a number between 1 and 10.");
System.out.println();
int attempts = 0;

do {
attempts++;

System.out.print("Enter your guess: ");
guess = input.nextInt();

if (guess == randomN) {
System.out.println("You won!");
} else if (guess < 1 || guess > 10) {
System.out.println("out of range");
attempts = +1;
} else if (guess > randomN) {
System.out.println("Too high");
} else if (guess < randomN) {
System.out.println("Too low");
}

} while (guess != randomN && attempts < 3);

if (guess != randomN && attempts == 3) {
System.out.println("Number is " + randomN);
}


}

}

最佳答案

您可以在 main 之外创建另一个静态方法,您可以在其中根据尝试输出自定义消息。

public static String describe(int attempts) {
switch(attempts) {
case 1: return "First guess: ";
case 2: return "Second guess: ";
case 3: return "Third guess: ";
default: return "Enter your guess: "; //should not happen
}
}

然后在你的main中像这样使用它:

...
do {
attempts++;

System.out.print(describe(attempts));
...
}

关于java - 简单的猜谜游戏。 "Your first guess is....",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34916898/

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