加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

为什么Java编译器会抱怨本地变量未在此处初始化?

发布时间:2020-12-15 02:05:14 所属栏目:Java 来源:网络整理
导读:int a = 1,b;if(a 0) b = 1;if(a = 0) b = 2;System.out.println(b); 如果我运行这个,我收到: Exception in thread "main" java.lang.Error: Unresolved compilation problem: The local variable b may not have been initialized at Broom.main(Broom.jav
int a = 1,b;
if(a > 0) b = 1;
if(a <= 0) b = 2;
System.out.println(b);

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

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不初始化变量?

解决方法

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

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

如果你真的想深入研究这个问题,Java语言规范的一整章专门讨论Definite Assignment的问题.这个案例与你的具体例子有关:

the rules do not accept the variation:

06001

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

这个特殊的例子(以及许多其他说明性的例子)可能似乎违背了你的期望,但这正是语言设计者想要的方式,所有编译器都必须遵守规则.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读