Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

        }
    }
}
like image 241
user1377384 Avatar asked Jul 30 '26 17:07

user1377384


1 Answers

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

like image 147
MByD Avatar answered Aug 01 '26 07:08

MByD