简体   繁体   中英

How to match the given output for Java Computer Guess Your Number Game; Binary Search

I have been having a lot of trouble with this and it is due soon, and I was wondering if anyone knows how to fix my problem. I have to create a program where: "Your task is to implement a number guesser that works on the principle of a binary search. In each step, the computer cuts the query interval in half. When the interval contains a single number, it proclaims the answer. The user of the program selects a number between 1 and 100. The computer is then asked to guess the number."

The sample output goes:

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.

My sample output in contrast goes:

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.

with some variation based on what edits I make.

The code is as follows:

//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;
            }
        }
    }
}
}

Of course this also has a tester class which is relatively short:

 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();
    }
}

Since you made an effort to solve the problem, I went ahead and restructured your Numbers class.

The first thing I did was get rid of the ArrayList. You can just as easily do arithmetic on integers as traverse the ArrayList.

I added a couple of integers, distance and direction. After each guess, the distance is cut in half. The computer guesses high or low until the distance is reduced to zero. At that point, the number is somewhere between the low and the high, inclusive.

The direction just tells us whether we need to guess lower (-1) or higher (+1) for the next guess.

I pulled the high low scanner code into its own method. It looks confusing at first, but all it does is tell us whether to guess higher (true) or lower (false). By moving this code into its own method, I could concentrate on the guessing logic.

Finally, I closed the scanner at the end of the processing.

//import statements
import java.util.Scanner;

public class Numbers {

    // constants to start the game
    private final int AT_LEAST = 0;
    private final int AT_MOST = 100;

    /**
     * Constructor of the Numbers() class
     */
    public Numbers() {

    }

    public void search() {
        int low = AT_LEAST;
        int high = AT_MOST;
        int guess = (low + high) / 2;
        int distance = guess / 2;
        int direction = 1;

        System.out.println("Guess a number between " + low + " and " + high
                + ".");

        Scanner in = new Scanner(System.in);

        do {
            boolean greaterThan = getHighLowResponse(in, direction, guess);
            if (greaterThan) {
                low = guess;
                guess += distance;
                direction = 1;

            } else {
                high = guess;
                guess -= distance;
                direction = -1;
            }
            distance /= 2;
        } while (distance != 0);

        for (int i = low; i <= high; i++) {
            System.out.println("Is your number " + i + "?");
            String finalAnswer = in.nextLine().toLowerCase();
            if (finalAnswer.equalsIgnoreCase("yes")) {
                System.out.println(i + " is the answer.");
                System.out.println("Thank you for playing the guessing game.");
                break;
            }
        }

        in.close();

    }

    private boolean getHighLowResponse(Scanner in, int direction, int guess) {
        do {
            System.out.println("Is your number " + getDirection(direction)
                    + " than " + guess + "?");
            String answer = in.nextLine().toLowerCase();
            if (direction < 0) {
                if (answer.equals("yes"))
                    return false;
                if (answer.equals("no"))
                    return true;
            } else {
                if (answer.equals("yes"))
                    return true;
                if (answer.equals("no"))
                    return false;
            }
        } while (true);
    }

    private String getDirection(int direction) {
        if (direction < 0) {
            return "less";
        } else {
            return "greater";
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM