2013-03-11 90 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