gpt4 book ai didi

java - Java 中的 "Guess the number"

转载 作者:行者123 更新时间:2023-12-01 22:20:38 26 4
gpt4 key购买 nike

我们打算用 java 创建一个程序,其中计算机随机猜测 1-100 之间的数字,并允许用户猜测该数字。如果该数字低于随机数,程序应该说:较低!对于更高,程序应该说:更高!如果用户猜对了数字,它应该说恭喜你在 X 次尝试中猜对了正确的数字,这就是我到目前为止所拥有的,当我在 cmd 中执行时,它只是垃圾邮件更高或更低,我需要帮助解决这个问题。

import java.util.Scanner;
import java.util.Random;

public class GuessingGame{

public static void main(String[] args) {

int random, guess, attempts;
Scanner keyboard = new Scanner(System.in);
Random generator = new Random();
random = generator.nextInt(100) + 1;
attempts = 1;

System.out.print("I am thinking of a number between 0 and 100, what do you think it is?");

guess = keyboard.nextInt();
while (guess != random) {
if (guess > random) {
System.out.print("Lower!");
attempts += 1;
}
else {
System.out.print("Higher!");
attempts +=1;
}
}

System.out.print(random + "is the correct answer and it took you" + attempts + "attempts to guess it!");

}
}

最佳答案

您只读取输入一次,然后永远循环(您在循环之外读取输入)。

尝试读取循环内的输入并使用do-while循环:

guess = 0;        

do {
guess = keyboard.nextInt();

if (guess > random) {
System.out.print("Lower!");
attempts += 1;
} else {
System.out.print("Higher!");
attempts +=1;
}
} while (guess != random);

关于java - Java 中的 "Guess the number",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29890213/

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