return two variables from one method

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

    You cannot return two different values in methods in Java.

    When this need occurs, you usually have two options:

    1. Create a class which has the types you want to return, and then return an instance of that class. Usually these classes are very basic, contain public members and optionally a constructor to initiate an instance with all the required values.
    2. Add a reference type object as a parameter to the method which the method will mutate with the values you want to return. In your example you use strings, and so this will not work since in Java strings are immutable.

    Another option would be to use an array of strings, since both your return types are strings. You could use this option as a return value, or a parameter which is altered by the method.

    Edit: usually "toString" methods do return only one string. Perhaps you should consider concatenating both your strings into one string using some separator. Example:

    return postn + "_" + movm;
    

提交回复
热议问题