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

问题描述

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)

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

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?

推荐答案

如果你改变第二个 code>到 else ,那么编译器会很高兴。

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);

如果你真的想深入这个问题,Java语言规范的一整章针对的问题。这种情况属于您的具体示例:

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:

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
}

必须引起编译时错误。

这个特定的例子(和许多其他说明性的)似乎违背了你的期望,但这正是语言设计者所希望的方式,所有编译器都必须遵守规则。

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编译器抱怨一个局部变量没有在这里初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 16:11