Unable to access a method's local variables outside of the method in Java

六眼飞鱼酱① 提交于 2020-05-22 07:57:05

问题


I am new to Java and am trying to access method variables outside of the method, but it doesn't work.

Code is below:

public class MethodAccess {
    public static void minus() {
        int a=10;
        int b=15;
    }

    public static void main(String[] args) {
        //Here i want to access variable names a & b that is in minus()
        int c = b - a;
    }
}

回答1:


Because a and b are local variables. If you want to access to them in your main method, you need to modify your code. For example :

public class methodacess {
       private static int a;
       private static int b;

       public static void minus(){   
           methodacess obj =new methodacess();
           a=10;
           b=15;    
       }   

       public static void main (String[] args){     
           int c = b - a;    
       }   
} 



回答2:


The variables that are defined inside a method are local to that method, so you cannot use them outside. If you want to use them outside, define instance variables in the beginning of your class.




回答3:


I think you might want to do it hte other way around:

public class methodacess {

     public int minus(int a, int b){   
          int c = b - a;
          return c;
     }   
     public static void main (String[] args){   
          // Here youi want to call minus(10, 15) 
          int a=10;
          int b=15;
          System.out.println("Result is: " + minus(a, b))
     }   
} 



回答4:


You need to define the variables as static class variables, so you can access them from a static function. Also watch out for the access modifiers, since when the variable is private you can't access them outside any other class.

public class methodacess {

   private static int a;
   private static int b;

   public static void minus(){   
      methodacess obj =new methodacess();
      a=10;
      b=15;
   }  

   public static void main (String[] args){   
      //Here i want to access variable names a & b that is in minus() 
      int c = b - a; 
   }   

} 


来源:https://stackoverflow.com/questions/34761523/unable-to-access-a-methods-local-variables-outside-of-the-method-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!