Is it possible to return more than one value from a method in Java?

I am using a craps simulator and I am trying to return two values ​​from the same method (or rather, I would like to).

When I wrote my return statement, I just tried putting "&". which compiled and works correctly; but I do not have access to the second return value.

public static int crapsGame(){ int myPoint; int gameStatus = rollagain; int d1,d2; int rolls=1; d1 = rollDice(); d2 = rollDice(); switch ( d1+d2 ) { case 7: case 11: gameStatus = win; break; case 2: case 3: case 12: gameStatus = loss; break; default: myPoint = d1+d2; do { d1=rollDice(); d2=rollDice(); rolls++; if ( d1+d2 == myPoint ) gameStatus = win; else if ( d1+d2 == 7 ) gameStatus = loss; } while (gameStatus == rollagain); } // end of switch return gameStatus & rolls; } 

When I return the value as:

 gameStatus=crapsGame(); 

It sets varaible accordingly to win or lose, but if I try something simple, following this statement with:

 rolls=crapsGame(); 

It is assigned the same value as gamestatus ... a 0 or 1 (win or lose). Any way I can access the second returned value? Or is there a completely different way of doing this?

+6
source share
6 answers

Create your own value holder object to save both values, and then return it.

 return new ValueHolder(gameStatus, rolls); 

It is possible to return an array with multiple values, but this is cryptic and it does nothing for readability. It is much easier to understand what that means ...

 valueHolder.getGameStatus() 

than that means.

 intArray[0] 
+9
source

return gameStatus & rolls means "return bit and game state and rolls", which is probably not what you want

You have several options:

  • return array
  • create a class that represents an answer with a property for each value and return an instance
  • use one of many java collections to return values ​​(possibly lists or maps).
+5
source

You can return an array of values ​​or a set of values.

+3
source

Is it possible to return more than one value from a method in Java?

No, it is not. Java allows only one value to be returned. This restriction is strictly related to the language.

However, there are several approaches to solving this limitation:

  • Write a lightweight holder class with fields for the multiple values ​​you want to return, and create and return an instance of this class.
  • Returns a Map containing the values. The problem with this (and the following) approach is that you stray into an area that needs to be checked for runtime type ... and this can lead to fragility.
  • Returns an array containing the values. The array must have a base type that will correspond to the types of all values.
  • If this is a method for an object, add several fields to the same object and methods that allow the caller to receive “auxiliary results” from the last call. (For example, the JDBC ResultSet class does this so that the client can determine if the value just received was NULL.) The problem is that this makes the class not reentrant at the instance level.
  • (You can even return additional results in statics, but this is a really bad idea. This makes the class irrecoverable for all instances, not to mention all the other errors associated with incorrect statistics.)

Of these, the first option is the cleanest. If you are concerned about the overhead of creating owner instances, etc., you might consider reusing the instances; for example, for the caller to transfer the existing “holder” to the called method in which the results should be placed.

+3
source

The best practice for the OOP approach is to return the object. An object that contains all the required values.

Example:

 class Main { public static void main(String[] args) { MyResponse response = requestResponse(); System.out.println( response.toString() ); } private static MyResponse requestResponse() { return new MyResponse( "this is first arg", "this is second arg" ); } } class MyResponse { private String x, y; public MyResponse( String x, String y ) { this.x = x; this.y = y; } @Override public String toString() { return "x: " + x + "\ty: " + y; } } 

If you need an even more scalable approach, you should use JSON responses. (let me know if you want an example with JSON too)

+2
source

You can do the following:

  • Use the Container class, for example

     public class GameStatusAndRolls { String gameStatus; String rolls; ... // constructor and getter/setter } public static GameStatusAndRolls crapsGame(String gameStatus, String rolls) { return new GameStatusAndRolls(gameStatus, rolls); } public static void main(String[] args) { ... GameStatusAndRolls gameStatusAndRolls = crapsGame(gameStatus, rolls); gameStatusAndRolls.getGameStatus(); 
  • Use List or array e.g.

     public static List<Integer> crapsGame(String gameStatus, String rolls) { return Arrays.asList(gameStatus, rolls); } private static final int GAME_STATUS = 0; private static final int ROOLS = 0; public static void main(String[] args) { ... List<Integer> list = crapsGame(gameStatus, rolls); ... list.get(0)...list.get(GAME_STATUS); ... list.get(1)...list.get(ROOLS); 

    or

     public static String[] crapsGame(String gameStatus, String rolls) { return new String[] {gameStatus, rolls}; } private static final int GAME_STATUS = 0; private static final int ROOLS = 0; public static void main(String[] args) { ... String[] array = crapsGame(gameStatus, rolls); ... array[0]...array[GAME_STATUS]; ... array[1]...array[ROOLS]; 
  • Use Map e.g.

     public static Map<String, String> crapsGame(String gameStatus, String rolls) { Map<String, String> result = new HashMap<>(2); result.put("gameStatus", gameStatus); result.put("rolls", rolls); return result; } public static void main(String[] args) { ... Map map = crapsGame(gameStatus, rolls); ... map.get("gameStatus")...map.get("rolls"); 
0
source

All Articles