简体   繁体   English

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

[英]How to pass a string from one method to another method in Java

I declared string: 我声明了字符串:

private String name;

1st method: 第一种方法:

private void showJSON(String response){
    name = collegeData.getString(Config.KEY_NAME);
}

I want to use the value of name in this method: 我想在这个方法中使用name的值:

private void setRealmData() {}

Your question is a bit unclear, but there are two distinct cases of how to implement this: 您的问题有点不清楚,但有两个不同的案例如何实现:

A. The name variable is an instance variable: 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. The name variable is a local variable: 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
    }
}

Note that the myClass class is a dummy class I used to show the scope of the variables and methods, adjust accordingly. 请注意, myClass类是一个虚拟类,我用它来显示变量和方法的范围,进行相应的调整。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将字符串变量 java 从一种方法传递到另一种方法 - How pass string variable java from one method to another method 我如何通过 ArrayList<string> 在 Java 中从一种方法到另一种方法。 变量未初始化错误</string> - How do I pass an ArrayList<String> from one method to another in Java. Variable not initialised error Java,将字符串从一种方法传递到另一种方法 - Java, Passing a String from one method to another 如何将变量从一种方法传递到另一种方法? - How to pass variables from one method to another? 如何将String值从一个void方法传递到另一个void方法 - How to pass String value from one void method to another void method 如何将值从一种方法传递到另一种方法 - How to pass the value from one method to another method 如何将链接列表从一种方法传递或检索到另一种方法? - How to pass or retrieve linked list from one method to another method? 在Java swing中将方法从一个类传递到另一个类 - pass a method from one class to another class in java swing 在java中将一个对象数组从一个方法传递给另一个方法 - pass an array of objects from one method to another in java 如何在Java中将字符串值从子方法传递到主方法? - How to pass String value from sub method to main method in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM