private static void algorithm2() {
String name = "";
int high = (char)90;
int low =(char) 66;
int letter;
int direction;
do {
letter = (high + low) / 2;
String[] choices = { "Before", "This is the letter", "After", "Done" };
direction = JOptionPane.showOptionDialog(null,
"Is the next letter in your name a(n) \'" +(char) letter
+ "\' or is it after/before it? ", "Option 2",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE,
null, choices, "Option 2");
if (direction == 0)
low= letter - 1; //
if (direction == 1){
name+=(char)letter;
}
if(direction==2){
high = letter + 1; // last guess was too high
}
if (direction == 3)
break;
} while (direction != 1);
JOptionPane.showMessageDialog(null, "Thanks for playing " + name + "!");
}
猜猜每个可能字母序列中的中间字母。第一次,这是m或n。每当做出猜测时,询问用户a)猜测是否正确,b)正确答案的字母顺序早于猜测,或c)正确的字母后来按字母顺序而不是猜测。相应地调整后续猜测,总是猜测剩余的可能字母组中的中间字母。当可能性的数量是偶数时,您是否猜测第一个或第二个“中间”字母并不重要。当只有一种可能性时,那一种是一个值列表中的中间选择。
我无法使其工作,当我出现窗口时,我点击之前显示错误的字母。
答案 0 :(得分:0)
正如人们在评论中指出的那样:
if (direction == 0)
low= letter - 1; //
应该是
high = letter - 1;
同样,
if(direction==2){
high = letter + 1; // last guess was too high
}
应该是
low = letter + 1;
此外,当direction == 1
终止循环时:
while (direction != 1);
因此用户无法填写超过1个字符,因此您应将其更改为while(true);
或while(direction != 3)
public static void main(String[] args) {
String name = "";
int direction;
do {
int high = (char) 90;
int low = (char) 66;
int letter;
do {
letter = (high + low) / 2;
String[] choices = { "Before", "This is the letter", "After",
"Done" };
direction = JOptionPane.showOptionDialog(null,
"Is the next letter in your name a(n) \'"
+ (char) letter
+ "\' or is it after/before it? ", "Option 2",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
null, choices, "Option 2");
System.out.println(direction);
if (direction == 0)
high = letter - 1; //
if (direction == 1 || direction == 3) {
name += (char) letter;
}
if (direction == 2) {
low = letter + 1; // last guess was too high
}
} while (direction != 1 && direction != 3);
} while (direction != 3);
JOptionPane.showMessageDialog(null, "Thanks for playing " + name + "!");
}
high == low
时要小心,如果用户不接受此字符,则应该是错误。