繁体   English   中英

如何在Java中将字符串从一个方法传递到另一个方法

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM