【发布时间】:2019-04-19 18:11:09
【问题描述】:
import java.util.Scanner;
public class GuessingGame {
private Scanner reader;
public GuessingGame() {
// use only this scanner, othervise the tests do not work
this.reader = new Scanner(System.in);
}
public void play(int lowerLimit, int upperLimit) {
instructions(lowerLimit, upperLimit);
boolean isAboveAverage;
int counter = -1;
while (counter < howManyTimesHalvable(upperLimit - lowerLimit)) {
isAboveAverage = isGreaterThan(average(lowerLimit, upperLimit));
if (upperLimit == lowerLimit) {
break;
}
if (isAboveAverage) {
lowerLimit = average(lowerLimit, upperLimit);
} else {
upperLimit = average(lowerLimit, upperLimit);
}
counter++;
}
System.out.println("your number is " + upperLimit);
}
// implement here the methods isGreaterThan and average
public boolean isGreaterThan(int number) {
boolean isGreater = false;
boolean isCorrectAnswerGiven = false;
while (!isCorrectAnswerGiven) {
System.out.println("Is your number greater than " + (number) + "? (y/n)");
String answer = reader.nextLine();
if (answer.equals("yes") || answer.equals("y")) {
isGreater = true;
isCorrectAnswerGiven = true;
} else if (answer.equals("no") || answer.equals("n")) {
isCorrectAnswerGiven = true;
}
}
return isGreater;
}
public int average(int upperLimit, int lowerLimit) {
return (upperLimit + lowerLimit) / 2;
}
public int average2(int firstNumber, int secondNumber) {
double res = (firstNumber + secondNumber) / 2.0;
Math.round(res);
//System.out.println(res);
return (int) res;
}
public void instructions(int lowerLimit, int upperLimit) {
int maxQuestions = howManyTimesHalvable(upperLimit - lowerLimit);
System.out.println("Think of a number between " + lowerLimit + "..." + upperLimit + ".");
System.out.println("I promise you that I can guess the number you are thinking with " + maxQuestions + " questions.");
System.out.println("");
System.out.println("Next I'll present you a series of questions. Answer them honestly.");
System.out.println("");
}
// a helper method:
public static int howManyTimesHalvable(int number) {
// we create a base two logarithm of the given value
// Below we swap the base number to base two logarithms!
return (int) (Math.log(number) / Math.log(2)) + 1;
}
}
我在调试此代码时遇到问题。在这堂课中,我应该实现一个简单的人工智能,它会根据你对“你的数字是否高于”+一个数字这个问题的回答来猜测一个数字。我的问题是一个。代码永远不会到达给定范围的末尾(因此,范围从 1 到 10,它永远不会猜测 1 或 10)和 b.是没有及时停止。 Java 经常多次重复一个问题,但程序应该在知道答案后立即说出答案。
我的错显然在于播放方法(为了完整起见,我包括了整个班级),我只是不知道在哪里。我的程序正常运行,因此不太可能出现拼写错误或编程错误。我必须在我的逻辑中做错了什么,但我不知道是什么。有人知道错误在哪里吗?
【问题讨论】: