Paul Z. Wu
2014-03-31 17:02:23 UTC
OK, you don't need to tell me that I should avoid 'goto'.... I just had a nested loop which I didn't want to repeat some code or refactor it into some other ways to do it (sometimes, just getting too lazy :-). Here came to the 'goto implementation'. Check the comment 'why not zero' and please explain it to me. Just for fun. Oh, yes, please don't use 'goto'!
public class MyGoto {
public static void main(String s[]) {
boolean g = true;
gotoLabel: // not used, just for illustration.
for (int m = 0; m < 4; m++) {
outerloop:
for (int k = 0; k < 3; k++) {
if (g) {
if (k * m == 4) {
m = -1; // why not zero?
g = false;
System.out.println("break here");
break outerloop; // Here effectively goto 'gotoLabel'.
}
System.out.println(m + " " + k);
} else {
System.out.println(m + " " + k);
}
}
//Dealing with the data....
}
}
}
Output:
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
break here
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
3 0
3 1
3 2
Paul Z. Wu
http://www.elookinto.com
public class MyGoto {
public static void main(String s[]) {
boolean g = true;
gotoLabel: // not used, just for illustration.
for (int m = 0; m < 4; m++) {
outerloop:
for (int k = 0; k < 3; k++) {
if (g) {
if (k * m == 4) {
m = -1; // why not zero?
g = false;
System.out.println("break here");
break outerloop; // Here effectively goto 'gotoLabel'.
}
System.out.println(m + " " + k);
} else {
System.out.println(m + " " + k);
}
}
//Dealing with the data....
}
}
}
Output:
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
break here
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
3 0
3 1
3 2
Paul Z. Wu
http://www.elookinto.com