尝试使用三元运算符初始化整数变量时,无效

发布于 2025-02-12 08:49:59 字数 840 浏览 3 评论 0原文

有人可以启发这背后的解释是什么?为什么会出现例外?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

靖瑶 2025-02-19 08:49:59

如果barbaznull它们不能与String连接在一起,则只能是一个有效的对象与另一个字符串+一起使用(它将隐式调用toString()在对象上)。您可能希望考虑使用一个空的字符串“”),这应该有效。

If bar or baz are null they can't be joined with a String, only a valid object can be used with another String and + (it will implicitly call toString() on the object). You may wish to consider using an empty String ("") instead, that should work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文