return two variables from one method

前端 未结 5 1769
小蘑菇
小蘑菇 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:15

    In Java, when you want a function to return multiple values, you must

    • embed those values in an object you return
    • or change an object that is passed to your function ~ dystroy

    You have two options (that I know of) here:

    Option 1: Return as a new 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 [] myArray = new string[2];
            myArray[0] = postn;
            myArray[1] = movm;
    
            return myarray; //returns as array
         }
    

    Option 2: Return as such

    Edited to show get set

        private String a;
        private String b;
    
        public void setPostN(String s)
        {
                a= s;
        }
    
        public String getPostN()
        {
                return a;
        }
    
        public void setMovm(String s)
        {
                a= s;
        }
    
        public String getMovm() 
        {
                return a;
        }
    

    with your method:

    public void 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);
    
            setPostN(postn);
            setMovm(movm);
    
           //no return, but available via calling getMovm() or getPostN()
         }
    

提交回复
热议问题