Return more than one value from a function in Java

后端 未结 6 1381
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 04:31

How to return more than one value from a function in Java? Can anyone give sample code for doing this using tuples? I am not able to understand the concept of tuples.

<
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-18 05:29

    What if what you are returning are of different data types just like your situation. Or for example, Lets say you are returning a String name and an integer age. You can you JSON from the org.json library. You can get the jar at http://www.java2s.com/Code/Jar/j/Downloadjavajsonjar.htm

    public JSONObject info(){
         String name = "Emil";
         int age = 25;
         String jsonString  ="{\"name\":\""+ name+"\",\"age\":"+ age +"}";
         JSONObject json = new JSONObject(jsonString);
         return json ;
    }
    

    Afterwards, if you want to get the data somewhere in your program, this is what you do:

    //objectInstanceName is the name of the instantiated class
    JSONObject jso = objectInstanceName.info();
    String name = jso.getString("name");
    int age = jso.getInt("age");
    System.out.println(name + " is "+ age + " years old");
    
    //Output will be like
    Emil is 25 years old
    

    Hope you try it. Or you can read more on JSON in java if you HAVEN'T.

提交回复
热议问题