基本java:猜数字二进制搜索

时间:2013-11-10 21:24:47

标签: java binary-search

好吧,所以用户认为(不键入)1到10之间的数字(例如),程序会提示用户“你的数字是否小于或等于X?”,然后用户输入对或错。 到目前为止,我已设法进行搜索间隔,但我不知道如何继续。 主要问题是,如果我被允许使用“正确”,我只允许使用true的假。那就没问题了。

import java.util.*;

public class GuessTheNumber {

public static void main (String[]args){

    Scanner scan = new Scanner (System.in);
    System.out.println("Think of a number between 1 and 10\n");

    double max = 10;
    double x = max/2;

    while (true){
        System.out.println("Is your number less than or equal to "+(int)x+" ?");
        String truth = scan.next();

        if(truth.equals("true")){
            x=x/2;
        }
        if(truth.equals("false")){
            x+=x/2;
        }
    }
    //The program breaks at some point
    System.out.println("Your number is: ");
 }
}

程序希望用户键入true或false,因此我们可以忽略其他任何内容。

2 个答案:

答案 0 :(得分:0)

您没有跟踪搜索间隔,并且您没有提供任何方式来结束循环。你会得到一个有效的无限循环。您需要存储下限和上限,并根据用户的输入修改它们。

// ints, not doubles.  Do you expect 3.14159 as the user's choice?
int lower = 1;
int upper = 10;
int guess = (lower + upper) / 2;  // guess, not x. Make the name meaningful.

然后,当用户说猜测高于他想到的数字时,改变上限:

upper = guess - 1;
guess = (lower + upper) / 2;

为其他案件做类似的事情。这是你的功课,而不是我的。

最后,你怎么知道你什么时候完成的?什么表明?

if (/* we are done */) {
    break;
}

您可能需要其他类型的循环,或将while(true)更改为其他类型的循环。并且,请不要在main()中执行所有操作。

答案 1 :(得分:0)

while循环的开头(内部)添加以下内容:

System.out.println("Is your number " + x +" ?");
String truth = scan.next();
if(truth.equals("true")){
    break;
}

其他选项:将您的if语句转换为如下所示:

if(truth.equals("true")){
    if(x == x/2) break;
    x=x/2;
}
if(truth.equals("false")){
    if(x == x + x/2) break;
    x+=x/2;
}

然后将最后一行输出更改为:

 System.out.println("Your number is: " + x);