I have this 2d array:
public int[][] intmap =
{
{0, 0, 0, 0, 0},
{0, 1, 2, 0, 0},
{0, 0, 2, 0, 0},
{0, 3, 0, 0, 0},
{0, 0, 0, 3, 3}
};
How can I move number 1 in the array without stepping on number 2 or 3? If the next step is one of them, I'd like to print out a warning message. I tried to use an exception because I don't want to go outside the map. Here's is an exeample of a direction (from my code):
public void goRight() {
try {
if (intmap[i][j + 1] != 2 && intmap[i][j + 1] != 3) {
intmap[i][j] = previousNumber;
previousNumber = intmap[i][j + 1];
intmap[i][j] = 1;
} else {
System.out.println("You can not move here!");
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("You can not move outside the the map!");
}
}
I tried to use ++j
at the beginning and without the if()
it worked fine. It didn't let me outside the map but I wanted to solve the "number 2 and 3" problem. So I made an if(){}else{}
but it didn't work really well. My friend told me I should use j+1
instead of ++j
but the character doesn't move in this case. previousNumber
is an int , where I store the number where number 1 was. In default, I give int previousNumber = 0
. I'm able to call the direction methods and print out the array.
I used ++j
instead of j+1
inside the if
statement.
public void goRight() {
try {
if (intmap[i][j + 1] != 2 && intmap[i][j + 1] != 3) {
intmap[i][j] = previousNumber;
previousNumber = intmap[i][++j];
intmap[i][j] = 1;
} else {
System.out.println("You can not move here!");
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("You can not move outside the the map!");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.