Java:对变量初始化概念感到困惑

发布于 2025-01-06 16:34:45 字数 1051 浏览 1 评论 0原文

我是 Java 新手,在理解变量声明和初始化的概念时遇到了一些困难。

例如,当我这样做时:

public class Foo {
    public static void main (String[] args) {
        int x, y;
        for (x = 0 ; x < 10 ; x++) {
           y = x + 1;
        }
        System.out.println(x);
        System.out.println(y);
    }
}

它不会编译并显示“变量 y 可能尚未初始化”。 但是,如果我告诉它在循环后打印出 x 值,它不会有任何问题。当然,如果我只是在开始时声明它(说 int y = 0; 或类似的东西),它会起作用,但我想知道为什么打印 x 而不是 y。

提前致谢!


编辑:

我知道编译器实际上并没有在循环内部检查变量是否会被初始化,所以它只是说它可能没有被初始化,但是为什么下面的代码可以工作呢?编译器是否检查 if 循环而不检查 for 循环?

public class Foo {
    public static void main (String[] args) {
        int x = 0, y;
        if (x == 0) {
            y = 1;
        }
        else {
            y = 2;
        }
        System.out.println(y);
    }
}

编辑2:

如果我实际上为 else 部分给出另一个条件,那么它看起来会给出相同的错误:

if (x == 0) {
    y = 1;
}
else if (x == 1) {
    y = 2;
}

所以我猜另一个例子是有效的,因为 y 在 if 和 else 部分中都被初始化了,这意味着无论给定的条件是什么,y 总是会被初始化。现在我真的明白了。谢谢你!!

I'm new to Java and I'm having a bit of trouble understanding the concept of the declaration and the initialization of variables.

For example, when I do:

public class Foo {
    public static void main (String[] args) {
        int x, y;
        for (x = 0 ; x < 10 ; x++) {
           y = x + 1;
        }
        System.out.println(x);
        System.out.println(y);
    }
}

It does not compile and says that "variable y might not have been initialized."
However, it does not have any trouble if I tell it to just print out the x value after the loop. Of course it would work if I simply declared it in the beginning (saying int y = 0; or something like that), but I wanted to know why x is printed but not y.

Thanks in advance!


Edit:

I understand that the compiler doesn't actually check inside the loop to see if the variable would be initialized or not so it just says it might not have been initialized, but then why does the following code work? Does the compiler check the if loop but not the for loop?

public class Foo {
    public static void main (String[] args) {
        int x = 0, y;
        if (x == 0) {
            y = 1;
        }
        else {
            y = 2;
        }
        System.out.println(y);
    }
}

Edit 2:

It looks like it gives me the same error if I actually give another condition for the else part so that it would be:

if (x == 0) {
    y = 1;
}
else if (x == 1) {
    y = 2;
}

So I guess the other example worked since y was initialized in both the if and the else part, which means the y would always be initialized no matter what the condition given is. Now I really get it. Thank you!!

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

雪若未夕 2025-01-13 16:34:45

局部变量没有默认值,您需要初始化它们。您确实设置了 x 的值 (x=0),但编译器不会检查循环体是否实际进入。因此,将 y 的值设置为 0

local variables don't have a default value and you need to initialize them. You are certainly setting the value of x (x=0), but the compiler doesn't check if the loop body will be actually entered. So give y a value of 0.

往事风中埋 2025-01-13 16:34:45

这是错误的:

   public class Foo {
        public static void main (String[] args) {
            int = x, y; // Wrong
            for (x = 0 ; x < 10 ; x++) {
               y = x + 1;
            }
            System.out.println(x);
            System.out.println(y);
        }
    }

这是正确的:

public class Foo {
    public static void main (String[] args) {
        int x, y; // Declaration only: x and y are uninitialized

这也是正确的:

public class Foo {
    public static void main (String[] args) {
        int x = 1, y = 10; // Declaration + initialization

'希望有帮助......

This is wrong:

   public class Foo {
        public static void main (String[] args) {
            int = x, y; // Wrong
            for (x = 0 ; x < 10 ; x++) {
               y = x + 1;
            }
            System.out.println(x);
            System.out.println(y);
        }
    }

This is correct:

public class Foo {
    public static void main (String[] args) {
        int x, y; // Declaration only: x and y are uninitialized

This is also correct:

public class Foo {
    public static void main (String[] args) {
        int x = 1, y = 10; // Declaration + initialization

'Hope that helps...

生活了然无味 2025-01-13 16:34:45

如果你查看你的代码;您已在 for 循环中将 x 初始化为 0,然后使用 x++ 递增它。但是您正在循环内初始化 Y,该循环可能会也可能不会在运行时执行(与编译时无关)。在Java中,在使用局部变量之前必须对其进行初始化,如果不这样做编译器会提示错误。这就是为什么打印 x 而不是 Y

If you look in your code; you have initialized x to 0 in for loop and then incrementing it with x++. But you are initializing Y inside loop which may or may not execute at runtime (nothing to do with compile time). In Java, you have to initialize local variable before using it and if you are not doing so compiler will prompt the error. And that is why x is printed and not Y

财迷小姐 2025-01-13 16:34:45

直到运行时才能确定 for 循环是否会运行一次。因此,初始化不算数(即编译器不能依赖它,因此会出错)。

在运行时之前无法确定将触发这两个子句(ifelse)中的哪一个。然而,在编译时我们知道其中一个或另一个将会触发,因此如果您在两者中进行初始化,编译错误就会消失。

It cannot be determined until run-time whether the for loop will be run even once. Therefore that initialization doesn't count (i.e., the compiler cannot depend on it, so it errors).

It cannot be determined until run-time which of the two -- the if or the else clause -- will fire. However, at compile-time we know that one OR the other will fire, so if you initialize in both, the compilation error goes away.

混浊又暗下来 2025-01-13 16:34:45

x 在 for 循环中初始化(第一个参数)

x gets initialized in the for loop (first argument)

时光磨忆 2025-01-13 16:34:45

会发生什么

for (x = 0 ; x < someOtherVariable ; x++) {

考虑一下如果您的循环是并且 someOtherVariable 的值碰巧为零, 。循环根本不会运行,因此 y 永远不会被初始化。

当然,您编写的循环将始终运行十次,因为下限和上限都是硬编码的,但编译器(显然)没有对代码进行足够的分析来证明这一点。它看到一个仅在循环内初始化的变量,并且遵循循环可能根本不运行的一般规则,它抱怨该变量可能未初始化。

顺便说一句,int = x, y; 不是有效的 Java 语法:等号不属于那里。

Consider what could happen if your loop was

for (x = 0 ; x < someOtherVariable ; x++) {

and the value of someOtherVariable happened to be zero. The loop wouldn't run at all, so y would never be initialized.

Of course, the loop you wrote will always run ten times since the lower and upper bound are both hard-coded, but the compiler (apparently) doesn't analyze the code enough to prove that. It sees a variable that's only initialized within a loop, and following the general rule that a loop might not run at all, it complains that the variable might not be initialized.

BTW, int = x, y; isn't valid Java syntax: the equals sign doesn't belong there.

肩上的翅膀 2025-01-13 16:34:45

它取决于两件事:

  • 无论什么都执行(此处为“x”)
  • 基于某些约束(此处为“y”)执行

编译器在任何情况下都会消除歧义,因此在有条件执行的块中见证变量初始化时会抛出错误。

It depends on two things:

  • executes no matter what (here "x")
  • executes based on some constraint (here "y")

The compiler repels ambiguity in any case so it throws error on witnessing a variable initialization in a block which is conditionally executed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文