该程序在用户播放时似乎与原始程序一样(实际上,玩这两个游戏的人不应该是能够告诉他们分开)。 在原始程序中,用户猜测1到100之间的随机数。在每次猜测后,程序会返回数字是高于还是低于猜测,直到用户猜测正确为止。数字猜测游戏,强制用户进行最大数量的猜测(Java)
但是,这个程序作弊。与其选择1-100范围内的随机数字,程序根本不会想到隐藏数字,而是以这样的方式回答 ,以便强制用户尽可能多地进行猜测。
我该如何做到这一点?我需要做一个if语句的循环吗?我现在认为可以做的唯一事情就是做一些其他的事情,我甚至不知道这是否会起作用。
我应该继续这个内在的if else的想法,但越来越具体吗?我只是觉得必须有更好的方法。
UPDATE *
好了,所以我想我已经想通了什么,我最初来的,但现在的程序卡住在一个无限循环当我选择与猜测相等的上下选择一个号码。任何想法为什么?
public static int feedback (Scanner console, int guess, int max) {
String sorry = "Sorry, that guess is incorrect.";
String lower = "The number I am thinking of is lower.";
String higher = "The number I am thinking of is higher.";
int guessCount = 0;
guess = console.nextInt();
int upperBound = max + 1;
int lowerBound = 0;
if (guess <= max && guess >= 1) {
guessCount = guessCount + 1;
if (max - guess < guess) {
System.out.println(sorry);
System.out.println(lower);
System.out.print("Your guess? ");
upperBound = guess;
guess = console.nextInt();
guessCount = guessCount + 1;
} else {
System.out.println(sorry);
System.out.println(higher);
System.out.print("Your guess? ");
lowerBound = guess;
guess = console.nextInt();
guessCount = guessCount + 1;
while (upperBound - lowerBound > 2) {
if (guess <= max && guess >= 1) {
if ((lowerBound + ((upperBound - lowerBound)/2)) < guess) {
System.out.println(sorry);
System.out.println(lower);
System.out.print("Your guess? ");
upperBound = guess;
guess = console.nextInt();
guessCount = guessCount + 1;
} else {
System.out.println(sorry);
System.out.println(higher);
System.out.print("Your guess? ");
lowerBound = guess;
guess = console.nextInt();
guessCount = guessCount + 1;
}
} else {
System.out.println("Your guess must be in the range 1-" + max + ". Try again.");
}
}
System.out.println("Yes, the number I was thinking of was " + guess);
}
} else {
System.out.println("Your guess must be in the range 1-" + max + ". Try again.");
return guessCount;
}
return guessCount;
}
从crapton开始! – iluxa
想一下这些限制:任何新的答案都不应该与过去的答案相矛盾。用户猜测的范围应该是最大的。然而,对于使用二分搜索的用户来说,作弊最多会迫使他做log2(n)猜测。 – Tarik
你在这里正确的轨道上。但请记住,可用的数字范围不断变化。如果用户猜测90并且你的程序显示“较低”,那么89是新的最高可能数字;现在排除90到100。同样,如果用户猜测20并且程序说“更高”,那么21是新的最低可能数字。您需要跟踪最低和最高可能的数字,并且每个猜测都会更改其中一个数字。 – steveha