To answer your question, a Array. We will each "." inside the array and the such pointer A. Such that it is initialized as:
String[][] square =
{{"A",".",".",".","."},
{".",".",".",".","."},
{".",".",".",".","."},
{".",".",".",".","."},
{".",".",".",".","."}};
now, we make a new method move(String direction, String[][] square), in which we make "A" move according to a set of rules:
Left - 0 y, -1 x
Right - 0 y, +1 x
Up - -1 y, 0 x
Down- +1 y, 0 x
To make:
public String[][] move(String direction, String[][] square) {
if (direction.equals("left")) {
try {
outerloop:
for (int i = 0; i < 5; i++){
for (int j = 0; j < 5; j++){
if (square[i][j].equals("A")) {
String temp = square[i][j];
square[i][j] = square[i][j-1];
square[i][j-1] = temp;
break outerloop;
}
}
}
} catch(Exception e) {
System.out.println("sorry you have reached the end of the square");
return square;
}
}
else if (direction.equals("right")) {
try {
outerloop:
for (int i = 0; i < 5; i++){
for (int j = 0; j < 5; j++){
if (square[i][j].equals("A")) {
String temp = square[i][j];
square[i][j] = square[i][j+1];
square[i][j+1] = temp;
break outerloop;
}
}
}
} catch(Exception e) {
System.out.println("sorry you have reached the end of the square");
return square;
}
}
else if (direction.equals("down")) {
try {
outerloop:
for (int i = 0; i < 5; i++){
for (int j = 0; j < 5; j++){
if (square[i][j].equals("A")) {
String temp = square[i][j];
square[i][j] = square[i+1][j];
square[i+1][j] = temp;
break outerloop;
}
}
}
} catch(Exception e) {
System.out.println("sorry you have reached the end of the square");
return square;
}
} else {
try {
outerloop:
for (int i = 0; i < 5; i++){
for (int j = 0; j < 5; j++){
if (square[i][j].equals("A")) {
String temp = square[i][j];
square[i][j] = square[i-1][j];
square[i-1][j] = temp;
break outerloop;
}
}
}
} catch(Exception e) {
System.out.println("sorry you have reached the end of the square");
return square;
}
}
return square;
}
Finally, initialize it during your loop and get square. Then use Arrays.deepToString() to print out the output.
Or to print in your format:
get each item and print it out using the loop your mentioned above:
for (int i = 0; i < 5; i++){
for (int j = 0; j < 5; j++){
System.out.print(board[i][j] + "\n");
}
}
Note: remember to replace square with the new square returned in the method!