The methods of a Java class may accept many passed arguments but they only returns either no value or only one value.
But most of the time, we need methods that return more than one value.
In that situation, we have 2 possibilities :
- the expected values have all the same data type and the same role or function
- the expected values have either different data types or their role are different
For the first possibility, the solution is simple :
if you know the exact number of the values, you have to make the method return an array;
if the number of values is not known, then you have to use the
List interface and you make the method return a
List.
For the second possibility, you'll have to build an object that will contain the values you wish and make the method return that object.
To do so, you'll have to write a new class.
For example, in your Tic Tac Toe program, you want your AI class a method that gives the x and y of the cell to play.
You may write a class called Position that will contain the values.
Example :
Code:
public class Position {
private int x;
private int y;
public Position(int x, int y) {
this.x = x;
this.y = Y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
public class AI {
...
public Position analyze(int[][] board) {
...
int x = something;
int y = something;
return new Position(x, y);
}
public class Starter {
...
...
int[][] b = { {0, 0, 0}, {0, 0, 0}, {0, 0, 0} };
AI ai = new AI();
Position position = ai.analyze(b);
int x = position.getX();
int y = position.getY();
...
...
}