return two variables from one method

前端 未结 5 1763
小蘑菇
小蘑菇 2021-02-08 04:30

How to write the following code correctly?

public String toString(int[] position, int xOffset, int yOffset) {
    String postn = String.format(\"[%d,%d]\", posit         


        
5条回答
  •  无人共我
    2021-02-08 05:04

    There are four method which I can think of to implement this scenario:

    1. Using a class

    Create a class with having all the attributes which you want to return, in your case it can be

    public class Sample {
       private String postn;
       private String movm;
       public String getPostn() {
            return postn;
       }
       public void setPostn(String postn) {
        this.postn = postn;
       }
       public String getMovm() {
           return movm;
       }
       public void setMovm(String movm) {
           this.movm = movm;
       }    
    }
    

    and change your method to include this class's object and set the values in these attributes. Change the return type of the method to Class name e.g. Sample

    public Sample toString(int[] position, int xOffset, int yOffset) {
        String postn = String.format("[%d,%d]", position[0], position[1]);
        String movm = String.format("[%d,%d]", xOffset, yOffset);
        Sample obj = new Sample();
        obj.setPostn(postn);
        obj.setMovm(movm);
        return obj;
    }
    

    2. Using an array

    Change the method to return String array and store the values in that array:

    public String[] toString(int[] position, int xOffset, int yOffset) {
        String postn = String.format("[%d,%d]", position[0], position[1]);
        String movm = String.format("[%d,%d]", xOffset, yOffset);
        String arr[] = new String[2];
        arr[0] = postn;
        arr[1] = movm;
        return arr;
    }
    

    3. Using javatuples

    You can read details at link http://www.javatuples.org/

    4. By delimiting Data

    You can use some delimiter if you are sure about the data in the variables. But this will require one spiting with the delimiter, when you want to use these values.

    public String toString(int[] position, int xOffset, int yOffset) {
        String postn = String.format("[%d,%d]", position[0], position[1]);
        String movm = String.format("[%d,%d]", xOffset, yOffset);
        return postn+"~"+movm;
    }
    

提交回复
热议问题