为什么 Java 编译器会抱怨本地变量没有在这里初始化? [英] Why does the Java compiler complain about a local variable not having been initialized here?

查看:46
本文介绍了为什么 Java 编译器会抱怨本地变量没有在这里初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int a = 1, b;如果(a > 0) b = 1;如果(a <= 0) b = 2;System.out.println(b);

如果我运行这个,我会收到:

<前>线程main"中的异常 java.lang.Error:未解决的编译问题:局部变量 b 可能尚未初始化在 Broom.main(Broom.java:9)

我知道局部变量没有初始化并且你有责任这样做,但在这种情况下,第一个 if 没有初始化变量?

解决方案

如果你把第二个 if 改为 else,那么编译器会很高兴.

int a = 1, b;如果(a > 0) b = 1;否则 b = 2;System.out.println(b);

如果你真的想深入研究这个问题,Java语言规范的一整章专门讨论明确分配.此案例与您的具体示例有关:

<块引用>

规则不接受变体:

void flow(boolean flag) {国际 k;如果(标志)k = 3;如果(!标志)k = 4;System.out.println(k);//k 在此之前不是确定分配的"}

所以编译这个程序一定会导致编译时错误发生.

这个特定示例(以及许多其他说明性示例)似乎出乎您的意料,但这正是语言设计者想要的方式,所有编译器都必须遵守规则.

int a = 1, b;
if(a > 0) b = 1;
if(a <= 0) b = 2;
System.out.println(b);

If I run this, I receive:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
 The local variable b may not have been initialized

 at Broom.main(Broom.java:9)

I know that the local variables are not initialized and is your duty to do this, but in this case, the first if doesn't initialize the variable?

解决方案

If you change the second if to else, then the compiler would be happy.

int a = 1, b;
if(a > 0) b = 1;
else b = 2;
System.out.println(b);

If you really want to go deep into this matter, one whole chapter of the Java Language Specification is dedicated to the issue of Definite Assignment. This case pertains to your specific example:

the rules do not accept the variation:

void flow(boolean flag) {
        int k;
        if (flag)
                k = 3;
        if (!flag)
                k = 4;
        System.out.println(k);  // k is not "definitely assigned" before here
}

and so compiling this program must cause a compile-time error to occur.

This particular example (and many other illustrative ones) may seem to defy your expectation, but this is exactly the way the language designers wanted it, and all compilers must abide by the rules.

这篇关于为什么 Java 编译器会抱怨本地变量没有在这里初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆