为什么这在if stitegent中无法实现?

发布于 2025-02-09 22:26:05 字数 865 浏览 0 评论 0原文

在Testone中:

  • 为什么“ else if”不可观(Anumber是最终的,因此编译器应该知道它不能超越“ If”部分,但只会发出警告)?
  • 由于“否则”显然是可以达到的,所以为什么“否则”部分无法实现(“ else if”始终是正确的)呢?

在Testtwo中:

  • “如果(true)”是无法实现的。

之所以这一切,是因为编译器以某种方式认为我的变量和布尔人也可以改变,即使它们是最终(“ Anumber”)和硬编码(“ true”)。而且,当没有变量或布尔值(在Testtwo中的第一个“否则”)时,什么都不会改变,并且因为它只是说“ else”知道它不能进一步到达任何东西,因为它可以扫除所有可能性吗?

public int testOne() {
        final int aNumber = 5;
        if (aNumber < 10) {
            return 0;
        } else if (true) {
            return 2;
        } else {
            return 3;
        }
    }

public int testTwo() {
        final int aNumber = 5;
        if (aNumber < 10) {
            return 0;
        } else {
            return 1;
        }
        if (true) {
            return 3;
        } else {
            return 4;
        }
    }

In testOne:

  • Why is the "else if" not unreachable (aNumber is final so the compiler should know it can't get past the "if" part, but it only gives a warning)?
  • Since "else if" apparently is reachable, why then is the "else" part not unreachable ("else if" is always true)?

In testTwo:

  • The "if (true)" is unreachable.

Is all this because the compiler somehow thinks my variable and boolean can change even if they are final("aNumber") and hardcoded("true"). And when there is no variable or boolean (the first "else" in testTwo) nothing can change, and since it mops up all possibilities by just saying "else" it knows it cant reach anything further down?

public int testOne() {
        final int aNumber = 5;
        if (aNumber < 10) {
            return 0;
        } else if (true) {
            return 2;
        } else {
            return 3;
        }
    }

public int testTwo() {
        final int aNumber = 5;
        if (aNumber < 10) {
            return 0;
        } else {
            return 1;
        }
        if (true) {
            return 3;
        } else {
            return 4;
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文