0

我有以下代码:

public class Java0102
{
    public static void main(String[] args)
    {
        int x = 2;
        int y = 10;
        if (x == 2)
        {
            x = 5;
            int w = y * x;
        }
        System.out.println("W="+w);
        int W = x*y*w;
        y = x;
        System.out.println("New W="+w);
        System.out.println("X="+x);
        System.out.println("Y="+y);
    }
}

当我尝试在 bluej 上编译它时,它说找不到符号 - 变量 w 但由于 if 语句运行,因为 x == 2 不应该 java 假定变量 w 已初始化并且存在?

4

3 回答 3

5

该变量w在块代码内声明if,这意味着它只能在该范围内访问:if语句的块代码。在该块之后,该变量w不再存在,因此编译器错误是有效的。

要解决这个问题,只需在语句之前声明并初始化变量if

int w = 1;
if (x == 2) {
    x = 5;
    w = y * x;
}

根据您对问题的评论:

我认为如果调用方法并且在方法内部声明的变量是本地的,因此范围会发生变化,因此在外部不可见。和 if 语句一样吗?它改变范围?

您混淆了类变量的概念,即字段和局部方法变量(通常称为变量)。当您创建类的实例时,类中的字段将被初始化,而方法中的变量具有特定的范围,具体取决于它们声明的块代码。

这意味着,您可以编译并运行此代码(并不意味着您必须编写这样的代码):

public class SomeClass {
    int x; //field
    public void someMethod(int a, int b) {
        int x = a + b;
        //this refers to the variable in the method
        System.out.println(x);
        //this refers to the variable in the class i.e. the field
        //recognizable by the usage of this keyword
        System.out.println(this.x);
    }
}
于 2015-04-27T20:04:51.130 回答
1

您的w变量需要在 if 语句之外声明。否则它超出范围

public class Java0102
{
    public static void main(String[] args)
    {
        int x = 2;
        int y = 10;
        int w = 1;  //declare and initialize your lowercase-w variable

        if (x == 2)
        {
            x = 5;
            w = y * x; //perform your arithmetic
        }
        System.out.println("W="+w);
        int W = x*y*w;
        y = x;
        System.out.println("New W="+w);
        System.out.println("X="+x);
        System.out.println("Y="+y);
    }
}
于 2015-04-27T20:04:59.603 回答
0

您的 w 仅在此块中可见:

{ x = 5; 整数 w = y * x; }

因此,在它之外,您无法访问它。如果需要,可以在 {} 块之外定义 w。

int w = 0;
{
            x = 5;
            w = y * x;
}
于 2015-04-27T20:09:26.310 回答