简体   繁体   中英

The Equals Function does not Work When it is In While Loop

I have code that is supposed to guess the user's number and it will narrow its search based on user input. The only issue is that within the while loop, the conditionals are not working with .equals. Instead, it skips to the else even when I type "less than". This is my code below, I am new to java so I might have made a mistake.

package reversedHiLo;
//Import utility
import java.util.*;

public class ReversedHiLo 
{

public static void main(String[] args) 
    {
        //create scanner class
        Scanner sc = new Scanner(System.in);
        System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
        int answer = sc.nextInt();
        //Create the first guess
        int guess = 1 + (int)(100*Math.random());
        //Create an array that stores the range of the player's number
        int[] range = new int[] {1,100};
        //While loop that guesses the number
        while(guess != answer)
        {
            System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
            String response = sc.next();
            sc.nextLine();
            //Conditionals to set the range of the guess
            if(response.equals("less than"))
            {
                range[1] = guess;
            }
            else
            {
                range[0] = guess;
            }
            //Guess a new number based on the range
            guess = range[0] + (int)((range[1] - range[0]) * Math.random());            
        }

        //Final print
        System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
        //Close scanner
        sc.close();
    }

}

There are two places where there is a problem:

  • The first one sc.nextInt() method - which only reads the int value by keeps current reading buffer on the same line. So to ignore/skip everything what is after int on the input line (which is probably \\n or \\r\\n if you only enter the number) you have to use sc.nextLine() .
  • The second one is sc.next() method - which only reads first token(or simply word) from your line. That is probably why you only get "less" value assigned to response and that will never be .equals to "less than" . So you will have to replace sc.next() one with sc.nextLine() and remove unnecessary sc.nextLine() from the next line.

Hope this should be clear now and you have a better understanding of what happens when you call these function. If not then I strongly advise you to have a look into Scanner class, read JavaDocs on write multiple tests around it to get a better understanding of what is going on.

If my explanation is still not clear have a look at the code I have modified for you below:

public static void main(String[] args)
{
    //create scanner class
    Scanner sc = new Scanner(System.in);
    System.out.println("Welcome to reverse number guessing game, pick a number between 1 and 100 and type it below:");
    int answer = sc.nextInt();
    sc.nextLine();   // This one is necessary to ignore everything on the same line as your number was typed in
    //Create the first guess
    int guess = 1 + (int)(100*Math.random());
    //Create an array that stores the range of the player's number
    int[] range = new int[] {1,100};
    //While loop that guesses the number
    while(guess != answer)
    {

        System.out.println("Is your number greater than or less than " + guess + "?" + Arrays.toString(range));
        String response = sc.nextLine();  // This reads the whole input line

        //Conditionals to set the range of the guess
        if(response.equals("less than"))
        {
            range[1] = guess;
        }
        else
        {
            range[0] = guess;
        }
        //Guess a new number based on the range
        guess = range[0] + (int)((range[1] - range[0]) * Math.random());
    }

    //Final print
    System.out.println("Your number was " + answer + ".\nThe computer's guess was: " + guess);
    //Close scanner
    sc.close();
}

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