有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在条件表达式中使用equals方法

为什么这个条件语句不起作用?? o1和o2是两个不同的物体

o1.equals(o2) ? System.out.println("Objects are equal"): System.out.println("Objects are not equal");


共 (5) 个答案

  1. # 1 楼答案

    尝试用这种方式替换代码

    System.out.println((o1.equals(o2) ? "Objects are equal" : "Objects are not equal"));
    
  2. # 2 楼答案

    这叫做ternary operator。里面不能有语句

    但你可以有表达方式

    String output = o1.equals(o2) ? "Objects are equal":"Objects are not equal";
    
  3. # 3 楼答案

    试试这个会有用的

    System.out.println(o1.equals(o2) ? "Objects are equal": "Objects are not equal");
    
  4. # 4 楼答案

    试试这个,conditional Operator

    System.out.println((o1.equals(o2) ? "Objects are equal": "Objects are not equal"));
    

    因为你的代码不是语句

  5. # 5 楼答案

    根据Java语言规范,在“条件运算符”下-

    It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.

    因为println是一个void方法,所以第二个和第三个操作数表达式满足这个条件。至于为什么它是这样工作的——这就是Java的定义方式