#not producing the correct midpoint on subsequent iterations

3 messages · Page 1 of 1 (latest)

hollow sorrel
#

I have a guessing game where the computer trys to guess a number between 1 and 100 and you enter either h or l to tell the computer if the number is too high or too low. According to my prof it isnt "producing the correct midpoint on subsequent iterations". Is there something obvious I'm missing that I can't see.

import java.util.Scanner;

public class HiLow {
    
    public static void main(String[] args) {
        
        int highRange = 100;
        int lowRange = 1;
        int guessCount = 0;
        
        // Ask to think of number then wait till any key is pressed
        System.out.println("Think of a number between 1 and 100 and then press enter.");
        Scanner in = new Scanner(System.in);
        in.nextLine();
        
        
        boolean playing = true;
        while(playing) {
            
            int numberToGuess = (lowRange + highRange) / 2;
            System.out.print("Is the number " + numberToGuess + " (Correct, Low, High) ? ");
            guessCount++;

            String userResponse = in.nextLine();
            if (userResponse.equalsIgnoreCase("h")) {
                highRange = numberToGuess;
            } else if (userResponse.equalsIgnoreCase("l")) {
                lowRange = numberToGuess;
            } else {
                System.out.println("Number of guesses: " + guessCount);
                playing = false;
            }
        }
        
    }
}
timber lichenBOT
#

This post has been reserved for your question.

Hey @hollow sorrel! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.