基本的Java:猜数字二进制搜索 [英] Basic java: Guess the number binary search
问题描述
好吧,因此用户认为(例如,不键入)介于1到10之间的数字,程序会提示用户您的数字是否小于或等于X?",然后用户键入对或错.到目前为止,我已经设法进行了搜索间隔,但是我不知道如何继续.主要问题是,如果允许我使用正确!",则只能使用true或false.那就没问题了.
Alright, so the user thinks (does not type it) of a number between 1 and 10 (for example), the program prompts the user "Is you number less than or equal to X?", then the user types either true or false. So far, I have managed to do the search interval, but I have no idea how to continue. Main problem is, I am only allowed to use true of false, if I was allowed to use "correct!" then there will be no problem.
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,因此我们可以忽略其他任何内容.
The program expects the user to type either true or false, so we can ignore anything else.
推荐答案
在 while
循环的开始(内部)添加以下内容:
Add the following at the beginning (inside) of your while
loop:
System.out.println("Is your number " + x +" ?");
String truth = scan.next();
if(truth.equals("true")){
break;
}
其他选项:将您的 if
语句转换为以下形式:
Other option: transform your if
statements to look like the following:
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;
}
,然后将最后一条输出行更改为:
and then change the last output line to:
System.out.println("Your number is: " + x);
这篇关于基本的Java:猜数字二进制搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!