【问题标题】:What is wrong with the code here causing if statement not to work [duplicate]这里的代码有什么问题导致if语句不起作用[重复]
【发布时间】:2022-08-17 01:29:45
【问题描述】:

为什么输入数字后我的if语句没有执行

public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println(\"enter 1 for convert time, enter 2 for digitssum:  \");
        String inputVal = sc.nextLine();  // Read user input
        //System.out.println(\"Input is: \" + inputVal);
        
        if (inputVal == \"1\")
        {
            System.out.println(\"enter a number to convert to time \");
            String inputVal2 = sc.nextLine();
            int inputVal3 = Integer.parseInt(inputVal2);
            System.out.println(\"Res is: \" + digitsSum(inputVal3));
        }
        else if (inputVal == \"2\")
        {
            System.out.println(\"enter a number to digitsum \");
            String inputVal2 = sc.nextLine();
            int inputVal3 = Integer.parseInt(inputVal2);
            System.out.println(\"Res is: \" + convertTime(inputVal3));
        }
        // Ask the user which game to play.
        // Then ask the user for input and pass the value to the corresponding method.
        
        // If the user enters 1, ask for an integer to convert and call the convertTime method.
        // If the user enters 2, ask for an integer and call the digitsSum method.
        
        // TODO: Your code goes here
        
        sc.close();
                System.out.println(\"test\");
    }
}
  • 对于字符串比较,您应该使用 inputVal.equals(\"1\") 而不是 inputVal == \"1\"

标签: java


【解决方案1】:

您正在使用 == 运算符来比较两个对象。在您的情况下,这两个对象永远不会相同(相等),因为它们是不同的独立对象。因此,您需要将对象的值与inputVal.eqauls("1") 进行比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多