0

So I was coding a simple game where the computer guesses a number you are thinking of between 1 and 1000. The code is as follows hwoever whenever I run this, no matter what i tell the computer wether i say higher or lower, it never updates the minimum and maximum to narrow in on the answer, ye the logic looks correct to me. :

package com.company;
import java.util.*;



public class Main {

    public static void main(String[] args) {
        //set and initialize variables
        int currentGuess;
        int min = 0;
        int max = 1000;
        boolean guessedCorrectly = false;
        String userInput;
        Random rand = new Random();

        //Create user input object
        Scanner user_input = new Scanner(System.in);

        //Explain Game Rules to User
        System.out.println("Please think of a number and I will try to guess it.");
        System.out.println("You can respond h for higher, l for lower, and c for correct: ");

        //Main Game Loop
        while (guessedCorrectly == false){
            currentGuess = min + rand.nextInt(max - min + 1);
            System.out.print("Is your number " + currentGuess);
            userInput = user_input.next();
            if (userInput == "h"){
                min = currentGuess;
            }else if (userInput =="l"){
                max = currentGuess;
            }else if (userInput == "c"){
                guessedCorrectly = true;
            }else{
                System.out.println("Please enter an h for higher, l for lower, or c for correct ");
            }


        }
        System.out.println("Congratulations to MEEEEEE, I guessed it correctly!");
    }
}

Any Ideas?

1 Answers1

0

change your if to check if the value of the string is equal and not the reference:

"l".equals(userInput)
vmrvictor
  • 683
  • 7
  • 25