我目前在一个Java 1类,并提出了一个数字猜谜游戏的乐趣。基本的输入,告诉你它是太高还是太低,然后让你再猜一次。我想这将是有趣的,使它,使计算机猜测以及,然后比较你的猜测,它的。我有所有的生成和比较工作,但它继续猜测数字,而不考虑大于/小于,我想补充。我有:
public static void autoPlay(int num){
Random rand = new Random();
int guess1 = rand.nextInt(100) + 1;
int counter = 0;
while(guess1 != num){
counter++;
int guess = rand.nextInt(100) + 1;
int initialHigh = 100;
int initialLow = 0;
// I want it to guess smart and recognize if it were too high or too low, and generate a number between there
if(guess1 > num){
int newGuess = rand.nextInt(initialHigh - guess1) + 1;
}else if(guess1 < num){
int newGuess2 = rand.nextInt(initialLow + guess1) + 1;
}
initialLow = guess;
initialHigh = guess;
guess1 = guess;
System.out.printf("%3d", guess1);
}
System.out.println("It took " + counter + " guesses to get the correct number");
}
我不知道if语句中的数学有什么问题,或者是否有什么我可以调用的东西。
2条答案
按热度按时间dly7yett1#
如果你想避免重复,那么生成适当的数字并将其随机排列(对于完全随机函数):
这个列表是完全随机排序的,所以你可以按照随机列表的顺序来猜测,因此索引就是猜测的次数(-1,因为它是索引的)
svmlkihl2#
你的代码的问题是你只是对随机数使用了相同的界限。您可以在此处生成新边界:
但是你根本不用它们,你只是重用了你以前的值:
你必须使用
newGuess
和newGuess2
产生的值(虽然你不需要这两个变量,但在if之外声明其中一个,然后在if中为其赋值)。然后,您将使用更新的值。我还注意到,你创建了许多存储相同值的变量,比如
guess
和guess1
,你不需要这些变量,你只需要声明其中一个变量,以后再重用(这样你就可以保存内存:))。另外,我发现将initialHigh和initialLow都设置为
guess
有问题,为什么要这样做?尝试检查您的代码逻辑并清理一些变量,其中一些是重复的。
但是,总的来说,我认为问题在于你正在生成新的边界,但你没有使用它们。