Reputation: 509
I have this code:
_leftArray[0] = _square[6][4];
_leftArray[1] = _square[8][4];
_leftArray[2] = _square[9][5];
I want to be able to extract the values of the array. I'd like to write a method that takes the array position as an argument and returns the coordinates. So if the method was called returnCoordinatesFromArray, I could type returnCoordinatesFromArray[1] and return 6 as a variable and 4 as a variable, so I could use them in another method.
Upvotes: 0
Views: 3429
Reputation: 95558
If these are static, hard-coded values, why not do something like this:
Map<Integer, int[]> indexToCoordinateMap = new LinkedHashMap<Integer, int[]>();
indexToCoordinateMap.put(0, new int[]{6, 4});
indexToCoordinateMap.put(1, new int[]{8, 4});
indexToCoordinateMap.put(2, new int[]{9, 5});
Then you don't need the method. You can simply get an array of values where the 0th
index is the x coordinate and the 1st
index is the y coordinate. Of course, this is by convention. If you want to be more specific, you can use Point
and do something like this:
Map<Integer, Point> indexToPointMap = new LinkedHashMap<Integer, Point>();
indexToPointMap.put(0, new new Point(6, 4));
indexToPointMap.put(1, new Point(8, 4));
indexToPointMap.put(2, new Point(9, 5));
Then you can simply do:
Point point = indexToPointMap.get(0);
Upvotes: 1
Reputation: 5662
"I could type returnCoordinatesFromArray[1] and return 6 as a variable and 4 as a variable" By design it is not possible in Java to return two values at once. If you need to do something like this you could either build your own little Object that holds two variables:
public class Tupel{
private int firstIndex;
private int lastIndex;
public Tupel(int firstIndex, int lastIndex){
this.firstIndex=firstIndex;
this.lastIndex=lastIndex;
}
public int getFirstIndex(){
return this.firstIndex;
}
// the same for lastIndex
}
Then you you store your Tupels in an array Tupel[] leftArray
where for example
leftArray[1] = new Tupel(6,4);
Or you use existing classes like Point
if they fit your needs.
Upvotes: 0
Reputation: 11197
Do a double for loop and save the x and y positions.
_square value;
int posX=0;
int posY=0;
for(int i=0; i<arr.length; i++) {
for(int j=0; j<arr.length; j++) {
if(arr[i][j]==value) {
posX=i;
posY=j;
}
}
}
Upvotes: 0