这个程序,当用户玩时,似乎就像原始程序一样(事实上,玩这两个游戏的人不应该分开它们)。 在原始程序中,用户猜测1到100之间的随机数。在每次猜测之后,程序返回数字是否高于或低于猜测,直到用户猜对。
然而,这个程序作弊。而不是选择1-100范围内的随机数,您的程序根本不会想到隐藏的数字,而是回答问题 以这种方式迫使用户尽可能多地猜测。
我怎样才能实现这一目标?我是否需要对if else语句进行for循环?我现在唯一能想到的事情就是如果不这样做,我甚至都不知道这是否会奏效。
我是否应该继续这种内在的否定想法,但是越来越具体了?我觉得必须有更好的方法。
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;
}
答案 0 :(得分:0)
每次猜测都会对可用的数字范围进行分区。
在第一次猜测之前,数字可以是1到100之间的任何数字。假设用户猜测“60”。这给了我们三种可能性:小于60,等于60,或大于60。
现在你需要决定这三种可能性中的哪一种会让用户猜测时间最长。我会给你一个提示:你不想说用户是正确的,直到只有一个号码供用户猜测,所以绝对不要接受“60”作为第一个猜测。
您应该能够编写一个接受输入的循环,然后根据输入决定如何回答。例如,如果用户的第一个猜测是“99”,那么你肯定希望你的程序说“太大”。让循环继续运行,直到只剩下一个答案。
祝你好运,玩得开心!
答案 1 :(得分:0)
从一些变量开始,以定义您当前的范围,即
int lower = 1;
int upper = 100;
创建一个吸引用户猜测的方法。这种方法应根据猜测如何划分范围,即最接近的界限来确定要替换的范围界限(尽可能长时间保持你的范围尽可能大)。然后它应该返回(或打印)更高或更低然后循环回到用户的另一个猜测
// For example
Starts lower = 1, upper = 100
User guesses 25
Replace lower with 25
say to guess higher
Get another guess range is now lower = 25, upper = 100
User guesses 75
replace upper with 75
say to guess lower
get another guess range is now lower = 25, upper = 75
etc, etc, etc, until guess has to be correct.