gpt4 book ai didi

java - 为什么 Java 编译器会提示局部变量没有在这里初始化?

转载 作者:搜寻专家 更新时间:2023-11-01 03:58:21 25 4
gpt4 key购买 nike

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:

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.

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

关于java - 为什么 Java 编译器会提示局部变量没有在这里初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2361916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com