【发布时间】:2016-11-12 23:13:12
【问题描述】:
提示:玩家选择一个范围(最小值和最大值),然后在该范围内思考一个数字(无需在程序中输入数字)。游戏应该使用二分搜索系统地猜测玩家的号码。玩家应该在回合之间告诉计算机“太高”或“太低”或“正确”。该程序应继续运行,直到计算机得到答案,或检测到作弊(或确定知道答案)。在退出之前,计算机应该会说出它有多少“轮”(猜了多少次)。
问题:计算机第一次出错,用户声明过高或过低后,我无法重新设置上下限的值
import java.util.Scanner;
public class TestPractice {
public static void main(String[] args) {
System.out.println("Think of a number");
Scanner scan = new Scanner(System.in);
String x = null;
String y = null;
String i = null;
//Get the input from the player
System.out.println("Please your maximum value");
if (scan.hasNext()) {
x = scan.next();
}
System.out.println("Please input your min value");
if (scan.hasNext()) {
y = scan.next();
}
//Parse the input so its usuable in the array
int max = Integer.parseInt(x);
int min = Integer.parseInt(y);
boolean numberguessed = true;
int numberofRounds = 0;
while(numberguessed) {
int midpoint = (max+min)/2;
numberofRounds++;
System.out.println("Is your number " + midpoint + " please say too low or too high or correct");
if (scan.hasNext()) {
i = scan.next();
}
if (i.equalsIgnoreCase("too high")) {
min = midpoint;
}
if (i.equalsIgnoreCase("too low")) {
max = midpoint;
min = 0;
}
if (i.equalsIgnoreCase("correct")) {
System.out.println("the number of rounds in this game is" + numberofRounds);
break;
}
}
}
}
【问题讨论】:
-
您的意思是要让用户再次输入
x和y最大值和最小值?在他们完成第一轮之后? -
还是不行?
标签: java binary-search