为什么我不能在方法之外看到方法局部变量?

时间:2015-03-20 05:34:06

标签: java methods local-variables

我是Java的新手,想要澄清一下,我明白我在方法参数中声明了一个x的int变量,但为什么会出现'结果&#39 ;无法解析变量。

public class Methods{

    public static void main(String[] args) {

        //f(x) = x * x
        square(5);
        System.out.println(result);

    }

    //This method 
    static int square(int x) {
        int result =  x * x;
    }

2 个答案:

答案 0 :(得分:1)

您可以,但请注意,局部变量仅在其受尊重的函数中定义。因此,即使在result中定义了square(),它也未在main()中定义。所以你要做的是为square函数返回一个值,并将其存储在main()内的变量中,如下所示:

public static void main(String[] args) {

    int myResult = square(5);
    System.out.println(myResult);
}

//This method 
static int square(int x) {
    int result =  x * x; // Note we could just say: return x * x;
    return result; 
}

Example Here

答案 1 :(得分:0)

既然你是初学者,我会彻底解释一下

规则1 :局部变量在方法,构造函数或块中声明。

规则2 :输入方法,构造函数或块时会创建局部变量,并且一旦退出方法,构造函数或块,变量将被销毁。< / p>

规则3 :局部变量没有默认值,因此应声明局部变量,并在首次使用前指定初始值。

public class Methods{

      public static void main(String[] args) {
            //f(x) = x * x
            square(5);
            System.out.println(result); //result! who are you? 
                  //Main will not recognize him because of rule 3.
           }


        static int square(int x) {
            int result =  x * x;  //you did it as said in rule 1
        }//variable result is destroyed because of rule 2.

请在代码中进行全面评论。

您的代码的解决方案是:

公共类方法{

  public static void main(String[] args) {
        //f(x) = x * x
        int result=square(5);
        System.out.println(result); //result! who are you? 
              //Main will not recognize him because of rule 3.
       }
    static int square(int x) {
        int result1 =  x * x;  //you did it as said in rule 1
        return result1;  
    }