【发布时间】:2015-04-03 09:08:04
【问题描述】:
如果您运行游戏,您会看到游戏无法正确猜出某些数字。例如,如果您的号码是 13,那么游戏将循环两次,并且还会猜测您的号码为 12 而不是 13。我认为这是计数的问题,但我尝试重复跟踪循环但找不到错误.我认为问题主要出在我的 while 循环中。
//import statements
import java.util.Scanner;
public class Numbers
{
public static void binarySearch()
{
int position=0;
String answer;
int upper_BOUND=100;
int lower_BOUND=0;
Scanner input=new Scanner(System.in);
while( (lower_BOUND <= upper_BOUND))
{
position = (lower_BOUND + upper_BOUND) / 2;
System.out.println("Is your value greater than " + position + "?");
answer=input.next();
if((upper_BOUND-lower_BOUND<=1))
{
break;
}
if (answer.equals("no")) // If the number is > key, ..
{ // decrease position by one.
upper_BOUND = position --;
}
if(answer.equals("yes"))
{
lower_BOUND = position ++; // Else, increase position by one.
}
}
System.out.println("Is your number " + position + "?");
String answer2=input.next();
System.out.println(position+" is the answer.\n Thank you for playing the guessing game.");
//else
// System.out.println("Bruh pick a number from 1 to 100 ");
}
}
…… 测试类
public class NumberGuesser
{
public static void main(String[] args)
{
int[ ] num = new int [100];
// Fill array
for (int i = 0; i <= 99; i++)
num[i]=i;
//The search method
Numbers.binarySearch();
}
}
【问题讨论】:
-
有什么问题。?
-
您在 NumberGuesser 类中创建了数组,但您没有在任何地方使用 :D 那么您在哪里搜索??
标签: java loops search while-loop binary-search