简体   繁体   中英

Invoke method with parameters in other method, in Java

I'm having a possible solution to the problem in my head but I don't quite know how to do that with code. I got stuck with invoking a method in a method in Java.

I have this code:

public Student getStudent(String queryWord){
    //the queryWord here should actually be the String result that returnQueryColumn returns

}

private static Map<String, String> returnMap(String myQuery){
    String[] params = myQuery.split("=");
    Map<String, String> myMap = new HashMap<String, String>();
    String myKey = params[0];
    String myValue = params[1];

    //myKey should be for example firstName, myValue should be the ACTUAL first name of the student
    myMap.put(myKey,myValue);

    return myMap;
}

private static String returnQueryColumn(Map<String, String> myMap){
    //here I want to get just the KEY from the myMap(from the returnMap method)
    //that key should be the column in my database, so I need this so that later on I can compare if the given key (firstName) is present in the database as a column

    String queryWord = returnMap().get(); //query should get firstName in my case

    return queryWord;
}

I know this code doesn't work, but I need some help, how can I achieve what I have in mind? I'm stuck at this - how can I invoke a method in other method, and make the string that is being returned in the first method to be a parameter in the second one.

Let's say you have Student class:

public class Student {
    String fullName;

    public Student(String fullName) {
        this.fullName = fullName;
    }
}

And, if I understood your intentions right, Main class can look like this.

Sample code prints student fullName property.

public class Main {

    public static void main(String[] args) {
        Student student = getStudent("john=John Appleseed");
        System.out.println(student.fullName);
    }

    public static Student getStudent(String myQuery) {
        return returnQueryColumn(myQuery);
    }

    private static Map<String, Student> returnMap(String myQuery){
        String[] params = myQuery.split("=");
        Map<String, Student> myMap = new HashMap<String, Student>();
        String myKey = params[0];
        String myValue = params[1];
        Student student = new Student(myValue);
        myMap.put(myKey, student);

        return myMap;
    }

    private static Student returnQueryColumn(String myQuery) {
        String[] params = myQuery.split("=");
        String key = params[0];
        return returnMap(myQuery).get(key);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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