Java条件问题

use*_*384 2 java debugging conditional conditional-statements

无论我做什么,当用户在控制台输入1时,这段代码永远不会评估为真...我很困惑为什么它评估为假...任何帮助都非常感谢.

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

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

MBy*_*ByD 8

应该是"1".equals(GameSelection),==比较对象的引用,同时equals比较内容.

此外,Java命名约定是以小写形式启动变量名称.(例如gameSelection,playHex等)

  • +1为"1".equals`并防止空指针异常. (2认同)