【问题标题】:Java conditional issueJava条件问题
【发布时间】:2012-05-15 00:50:33
【问题描述】:

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

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

        }
    }
}

【问题讨论】:

    标签: java debugging conditional conditional-statements


    【解决方案1】:

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

    此外,Java 命名约定是以小写开头的变量名。 (例如gameSelectionplayHex 等)

    【讨论】:

    • +1 表示"1".equals 并防止出现空指针异常。
    • @amir 老实说,我不知道我是否想要。如果您将 null 传递给不应该拥有它的方法,那么您需要一个异常。否则,您的代码可能会默默地失败,而您不会知道。
    • @user1377384 如果他解决了你的问题,不如你给 Binyamin 一点爱,然后点击左侧的已接受答案复选标记?
    • @corsiKa - 我认为这是风格问题,我不喜欢这种风格,但在某些情况下它很方便。
    • @AmirRaminfar 我从来不知道 .equals() 实际上会检查空值。今天学到了新东西:)
    【解决方案2】:

    Java 没有运算符重载。

    您必须使用.equals(...)。否则,您正在比较参考地址。

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

    【讨论】:

      【解决方案3】:

      你需要:

      if(GameSelection.equals("1"))
      

      代替:

      if(GameSelection == "1")
      

      ==用于检查2个引用是否引用了内存中的同一个对象,而equals()检查了2个引用是否引用了内存中的同一个对象OR为2不同的对象但具有相同的值(2 个字符串是等效的)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-06-16
        • 2011-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-13
        • 2015-09-28
        • 2020-03-21
        相关资源
        最近更新 更多