为什么这个条件语句不起作用? o1和o2是两个不同的对象。
o1.equals(o2) ? System.out.println("Objects are equal"): System.out.println("Objects are not equal");
答案 0 :(得分:4)
试试这个,conditional Operator
System.out.println((o1.equals(o2) ? "Objects are equal": "Objects are not equal"));
因为您的代码不是声明。
答案 1 :(得分:4)
这称为ternary operator。你不能在其中有陈述。
但你可以有表达。
String output = o1.equals(o2) ? "Objects are equal":"Objects are not equal";
答案 2 :(得分:2)
尝试以这种方式替换您的代码
System.out.println((o1.equals(o2) ? "Objects are equal" : "Objects are not equal"));
答案 3 :(得分:2)
来自Java语言规范,在“条件运算符” -
下第二个或第三个操作数表达式是void方法的调用是编译时错误。
由于println
是一个void方法,因此第二个和第三个操作数表达式符合此条件。至于为什么它以这种方式工作 - 这就是Java定义的方式。
答案 4 :(得分:0)
试试这个会起作用
System.out.println(o1.equals(o2) ? "Objects are equal": "Objects are not equal");