gpt4 book ai didi

java - 条件表达式缺少 Java 错误?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:28:39 25 4
gpt4 key购买 nike

使用方法 test1()test2(),我得到一个Type Mismatch Error: Cannot convert from null to int,这是正确的;但为什么我在方法 test3() 中没有得到相同的结果?在这种情况下,Java 如何以不同方式评估条件表达式? (显然,NullPointerException 将在运行时出现)。是遗漏错误吗?

public class Test {

public int test1(int param) {
return null;
}

public int test2(int param) {
if (param > 0)
return param;
return null;
}

public int test3(int param) {
return (param > 0 ? param : null);
}

}

提前致谢!

最佳答案

当您混合使用运算符的类型时,条件运算符非常棘手;这是许多人的主题Java Puzzlers .

这是一个经典的例子:

System.out.println(true ? Integer.valueOf(1) : Double.valueOf(2));
// prints "1.0"!!!

还有一个:

System.out.println(true ? '*' : 0);     // prints "*"
int zero = 0;
System.out.println(true ? '*' : zero); // prints "42"

而且,正如您刚刚发现的那样:

System.out.println(true  ? 1 : null);   // prints "1"
System.out.println(false ? 1 : null); // prints "null"

了解条件运算符 ?: 的所有错综复杂之处可能非常困难。最好的建议是不要在第二个和第三个操作数中混用类型。

以下引述是Java Puzzlers, Puzzle 8: Dos Equis类(class)的节选:

In summary, it is generally best to use the same type for the second and third operands in conditional expressions. Otherwise, you and the readers of your program must have a thorough understanding of the complex specification for the behavior of these expressions.

JLS 引用

关于java - 条件表达式缺少 Java 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2986796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com