尝试使用三元运算符初始化整数变量时,无效
有人可以启发这背后的解释是什么?为什么会出现例外?
package integerProblem;
public class Test {
public enum Letter{
A, B, C;
}
public static void main(String[] args) {
Letter foo = Letter.C;
Integer bar = Letter.A == foo ? 1 : null; // bar is set to null.
System.out.println("Value of bar: " + bar);
Integer baz = Letter.A == foo ? 1 : Letter.B == foo ? -1 : null; // com.sun.jdi.InvalidTypeException: Generated value (null) is not compatible with declared type (int). occured invoking method.
System.out.println("Value of bar: " + baz);
}
}
输出:
Value of bar: null
Exception in thread "main" java.lang.NullPointerException
at integerProblem.Test.main(Test.java:15)
Can someone enlighten what is the explanation behind this? Why is an exception thrown?
package integerProblem;
public class Test {
public enum Letter{
A, B, C;
}
public static void main(String[] args) {
Letter foo = Letter.C;
Integer bar = Letter.A == foo ? 1 : null; // bar is set to null.
System.out.println("Value of bar: " + bar);
Integer baz = Letter.A == foo ? 1 : Letter.B == foo ? -1 : null; // com.sun.jdi.InvalidTypeException: Generated value (null) is not compatible with declared type (int). occured invoking method.
System.out.println("Value of bar: " + baz);
}
}
Output:
Value of bar: null
Exception in thread "main" java.lang.NullPointerException
at integerProblem.Test.main(Test.java:15)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果
bar
或baz
是null
它们不能与String
连接在一起,则只能是一个有效的对象与另一个字符串
和+
一起使用(它将隐式调用toString()
在对象上)。您可能希望考虑使用一个空的字符串
(“”
),这应该有效。If
bar
orbaz
arenull
they can't be joined with aString
, only a valid object can be used with anotherString
and+
(it will implicitly calltoString()
on the object). You may wish to consider using an emptyString
(""
) instead, that should work.