[英]How to pass a string from one method to another method in Java
我聲明了字符串:
private String name;
第一種方法:
private void showJSON(String response){
name = collegeData.getString(Config.KEY_NAME);
}
我想在這個方法中使用name的值:
private void setRealmData() {}
您的問題有點不清楚,但有兩個不同的案例如何實現:
A. name
變量是一個實例變量:
public class myClass{
private String name;
private void showJSON(String response){
// name = collegeData.getString(Config.KEY_NAME); - this was your code
this.name = collegeData.getString(Config.KEY_NAME); // Set the 'name' variable to the value you want for this instance
setRealmData(); // No argument passed, provided that 'name' is an instance variable
}
private void setRealmData(){
System.out.println(this.name); // Sample code
}
}
B. name
變量是一個局部變量:
public class myClass{
private void showJSON(String response){
String name;
// name = collegeData.getString(Config.KEY_NAME); - this was your code
name = collegeData.getString(Config.KEY_NAME); // Set the 'name' variable to the value you want for the method
setRealmData(name); // Single argument passed, provided that 'name' is a local variable
}
private void setRealmData(string name){
System.out.println(name); // Sample code
}
}
請注意, myClass
類是一個虛擬類,我用它來顯示變量和方法的范圍,進行相應的調整。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.