2013-03-11 94 views
-1

我試圖訪問函數內部的變量X,但我似乎無法訪問它。 我有一個函數「行動()」內部函數變量

public void Action(){ 

    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 

    try { 
    String response = null; 
    try { 
     response = CustomHttpClient.executeHttpPost("http://www.xxxx.com/xxxx.php", 
                postParameters); 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

    String result = response.toString(); 

    //parse json data 
    try { 
     returnString = ""; 
     JSONArray jArray = new JSONArray(result); 
     for (int i=0; i<jArray.length(); i++) { 

     JSONObject json_data = jArray.getJSONObject(i); 
     Log.i("log_tag","id: "+json_data.getInt("id")+ 
       ", name: "+json_data.getString("name")+ 
       ", sex: "+json_data.getInt("sex")+ 
       ", birthyear: "+json_data.getInt("birthyear")); 
     X = json_data.getInt("birthyear"); 
     returnString += "\n" + json_data.getString("Time") + " -> "+ json_data.getInt("Value"); 
     } 
    } catch(JSONException e){ 
     Log.e("log_tag", "Error parsing data "+e.toString()); 
    } catch(Exception e){ 
     Log.e("log_tag","Error in Display!" + e.toString());;   
    } 
    } 
} 

我希望能夠訪問的變量「X」的方法之外,但它總是告訴我說,X沒有宣佈。

回答

0

根據需要在方法內聲明X實例變量或局部變量。

如果你想從任何實例方法訪問這個變量,然後聲明它的實例變量或如果你想使範圍本地然後聲明它的方法。

public class MainActivity extends Activity { 
    .... 
    private int X; //Way to declare the instance variable. 
    .... 

    private void methodName() { 
    { 
     private int X; //Way to declare the local variable. 
    } 
} 

在Java中,您需要在使用它之前聲明變量。你正在初始化它,而沒有聲明它。

0
void method(){ 

    int foo; //this is called variable declaration 

    //some where else in code 
    foo = 12; //this is called initialization of the variable 

    int fooBar = foo + bar; 

} 

上面的例子顯示了METHOD LEVEL SCOPE。變量foo將不能在方法範圍外訪問。

  • 類範圍
  • 環路範圍
  • 法適用範圍

Vairable scopes in Java

1

在Java(和大多數其他語言),也有所謂的 「範圍」,讓我們來限制「塊「 這裏。 一個塊基本上是包含在{}中的單個表達式的集合。

看一看這個僞例如:在內部塊

{ // outer block 
    int a = 1; 
    { // inner block 
     int b = 1; 
    } 
} 

您可以在外部塊不能看到b,這就是爲什麼你既不能訪問訪問兩個ab而也不會改變它(所以你只能在外部塊中看到a