我在这方面遇到了很多麻烦,很快就要到期了,我想知道是否有人知道如何解决我的问题。我必须创建一个程序,其中:“您的任务是实现一个基于二进制搜索原理工作的数字猜测器。在每一步中,计算机将查询间隔减半。当间隔包含单个数字时,它会宣布答案。程序的用户选择 1 到 100 之间的一个数字。然后要求计算机猜测这个数字。
示例输出如下:
Is your number greater than 50? (computer is asking this)
no (user responds with yes or no)
Is your number greater than 25?
no
Is your number greater than 13?
no
Is your number greater than 7?
yes
Is your number greater than 10?
yes
Is your number greater than 12?
yes
Is your number 13?
yes
13 is the answer. (computer declares final answer)
Thank you for playing the guessing game.
相比之下,我的示例输出为:
Is your number greater than 50?
no
Is your number greater than 25?
no
Is your number greater than 13?
no
Is your number greater than 7?
yes
Is your number greater than 10?
yes
Is your number greater than 11?
yes
Is your number greater than 12?
yes
Is your number 12?
yes
12 is the answer.
Thank you for playing the guessing game.
根据我所做的编辑有一些变化。
代码如下:
//import statements
import java.util.Scanner;
import java.util.ArrayList;
public class Numbers
{
//constant to initialize the ArrayList
private final int AT_MOST = 100;
//anArrayList of type ArrayList<Integer> which is to hold the values from 1 - 100
private ArrayList<Integer> anArrayList;
/**
* Constructor of the Numbers() class which initializes all of the instance fields
*/
public Numbers()
{
anArrayList = new ArrayList<Integer>();
int i =0;
//while loop to initialize anArrayList with values from 1-100
while(i < AT_MOST)
{
anArrayList.add(i+1);
i++;
}
}
public void search()
{
int low = 0;
int high = anArrayList.size();
int i = 0;
int j = 0;
while(low <= high)
{
int mid = (low + high)/2;
mid = anArrayList.get(mid - 1);
Scanner in = new Scanner(System.in);
System.out.println("Is your number greater than " + mid + "?");
String answer = in.nextLine();
if(answer.equalsIgnoreCase("yes"))
{
low = mid + 1;
}
else if (answer.equalsIgnoreCase("no"))
{
high = mid - 1;
low++;
}
if(low == high+1)
{
Scanner in2 = new Scanner(System.in);
System.out.println("Is your number " + mid + "?");
String finalAnswer = in2.nextLine();
if(finalAnswer.equalsIgnoreCase("yes"))
{
System.out.println(mid + " is the answer.");
System.out.println("Thank you for playing the guessing game.");
low = high + 1;;
}
else
{
System.out.println("Please play again, something went wrong!");
low = high + 1;
}
}
}
}
}
当然,这也有一个相对较短的测试器类:
public class NumbersGuesser
{
public static void main(String[] args)
{
//creates a new numbers object
Numbers newNumber = new Numbers();
//run method is called, game is played.
newNumber.search();
}
}