当用户玩这个程序时,看起来就像原来的程序一样(事实上,玩这两个游戏的人应该无法区分它们)。 在原始程序中,用户猜测一个介于 1 和 100 之间的随机数。每次猜测后,程序都会返回该数字是高于还是低于猜测值,直到用户猜对为止。
但是,这个程序作弊。与选择 1-100 范围内的随机数不同,您的程序根本不会考虑隐藏的数字,而是以强制用户进行尽可能多的猜测的方式进行回答。
我怎样才能做到这一点?我是否需要执行 if else 语句或其他内容的 for 循环?我现在唯一能想到的就是做一大堆 if else,我什至不知道这是否会奏效。
我是否应该继续这种内在的 if else 想法,但越来越具体?我只是觉得必须有更好的方法。
更新*
好的,所以我想我已经弄清楚了我最初的目的,但是现在当我选择一个上下选项相等的数字进行猜测时,程序陷入了无限循环。知道为什么吗?
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;
}