2

No matter what I do this piece of code will never evaluate to true when the user inputs 1 at the console... I'm confused as to why it is evaluating to false.. any help is much appreciated.

import java.io.*;
public class Default 
{
    public static void main(String [] args)
    {
        System.out.println("Welcome to the CS conversation game\n");
        System.out.println("Choose your game\n1)Hex to Decimal\n2)Binary to Decimal");
        Hex2Decimal PlayHex = new Hex2Decimal();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String GameSelection = null;
        try 
        {
            GameSelection = br.readLine();
        }
        catch (IOException ex) 
        {
            ex.printStackTrace();
        }
        if(GameSelection == "1")
        {
            PlayHex.Play();

        }
    }
}

3 Answers 3

8

Should be "1".equals(GameSelection), == compares references of objects, while equals compares content.

Also, the Java naming convention is to start variable names in lower case. (e.g. gameSelection, playHex etc.)

Sign up to request clarification or add additional context in comments.

11 Comments

+1 for "1".equals and protecting against null pointer exception.
@amir I don't know if I would want that, honestly. If you're getting a null passed into a method that shouldn't have it, you want an exception. Otherwise, your code may be silently failing and you wouldn't know it.
@user1377384 If he solved your problem, how about you show Binyamin a little love and click the accepted answer checkmark on the left?
@corsiKa - I think it's a matter of style, I'm not a fanat of this style, but it comes handy in some situations.
@AmirRaminfar I never knew that .equals() actually checks for null values. Learned something new today :)
|
4

You need:

if(GameSelection.equals("1"))

instead of:

if(GameSelection == "1")

== is used to check if the 2 references refer to the same object in the memory, while equals() checks whether the 2 references refer to the same object in the memory OR to 2 different objects but with the same values (the 2 strings are equivalent).

Comments

3

Java doesn't have operator overloading.

You will have to use .equals(...). Otherwise, you are comparing the reference address.

if(GameSelection.equals("1"))
{
   PlayHex.Play();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.