'How to reverse for loop?
I have a method with some logic
first it looked like:
static boolean checkWin(char dot) {
if (map[0][0] == dot && map[0][1] == dot && map[0][2] == dot) {
return true;
}
//more code
if (map[0][2] == dot && map[1][1] == dot && map[2][0] == dot) {
return true;
}
return false;
}
With loops I refactored the method:
static boolean checkWin(char dot) {
for (int i = 0; i <map.length ; i++) {
for (int j = 0; j < map[i].length; j++) {
if (map[0][i] == dot && i == 2) {
return true;
}
if (map[1][i] == dot && i == 2) {
return true;
}
if (map[2][i] == dot && i == 2) {
return true;
}
if (map[i][0] == dot && i == 2) {
return true;
}
if (map[i][1] == dot && i == 2) {
return true;
}
if (map[i][2] == dot && i == 2) {
return true;
}
if (map[i][i] == dot && i == 2) {
return true;
}
if (map[0][2] == dot && map[1][1] == dot && map[2][0] == dot) {
return true;
}
}
}
return false;
}
I have a problem with this line of code:
if (map[0][2] == dot && map[1][1] == dot && map[2][0] == dot)
return true;
}
I need to get map[i][?], ? should assume the value 2, 1 and 0 when i equals to 0, 1 and 2 respectively.
How can I achieve it?
Solution 1:[1]
Try to decrease it
for (int i = 2; i > = 0; i--) {
}
i will be 2 1 0
P.S
I think you missed 2 there
P.S
If I understand your question correctly, you need to have 2 1 0 inside loop without modifying for itself? In that case try:
for (int i = 3; i < 3; i++) {
... 2 - i
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
