2016-01-13 123 views
0

我是新來的java和我試圖訪問外面的方法變量,但它不起作用。代碼如下,無法訪問java以外的方法變量

public class methodacess { 

    public static void minus(){ 
     methodacess obj =new methodacess(); 
     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; 
    } 

} 

在此先感謝!

+0

嗯不,不會。局部變量(在方法中聲明)只在該方法調用的整個生命週期內存在。你需要聲明它的聲音。 –

+0

是的,那些是*局部變量*,並且它們在其範圍之外不可見。您需要以不同的方式構建您的代碼。 – Thilo

+1

順便說一下,開始一個類名稱與大寫(也許使用駱駝的情況下)是有點傳統,所以你的類名應該是方法訪問​​....但作爲一個注意:) –

回答

2

因爲ab是局部變量。 如果你想在你的主要方法中訪問它們,你需要修改你的代碼。例如:

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;  
     } 
} 
+0

它不起作用..你可以測試和修改代碼嗎? –

+0

是的,對不起,我忘了靜態的keywork – Julien

2

方法中定義的變量對於該方法而言是本地的,因此您不能在外部使用它們。如果你想在外面使用它們,在你的課程開始時定義全局變量。

2

我想你可能想這樣做,HTE各地的其他方式:

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)) 
    } 
} 
1

您需要定義變量爲靜態類變量,這樣你就可以從一個靜態函數訪問它們。還要注意訪問修飾符,因爲當變量是私人的時候,你不能在任何其他類之外訪問它們。

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; 
    } 

}