user1377384
user1377384

Reputation: 89

Java conditional issue

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

        }
    }
}

Upvotes: 2

Views: 91

Answers (3)

Eng.Fouad
Eng.Fouad

Reputation: 117607

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).

Upvotes: 4

Daniel A. White
Daniel A. White

Reputation: 190976

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

Upvotes: 3

MByD
MByD

Reputation: 137382

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.)

Upvotes: 8

Related Questions