1.标签

  1. //i=0
  2. //k=0
  3. //k=1
  4. private static void loop1() {
  5. for1:
  6. for (int i = 0; i < 3; i++) {
  7. System.out.println("i=" + i);
  8. for (int j = 0; j < 3; j++) {
  9. for (int k = 0; k < 3; k++) {
  10. System.out.println("k=" + k);
  11. if (k == 1) {
  12. break for1;
  13. }
  14. }
  15. }
  16. }
  17. }
  1. //i=0
  2. //k=0
  3. //k=1
  4. //i=1
  5. //k=0
  6. //k=1
  7. //i=2
  8. //k=0
  9. //k=1
  10. private static void loop2() {
  11. for1:
  12. for (int i = 0; i < 3; i++) {
  13. System.out.println("i=" + i);
  14. for (int j = 0; j < 3; j++) {
  15. for (int k = 0; k < 3; k++) {
  16. System.out.println("k=" + k);
  17. if (k == 1) {
  18. continue for1;
  19. }
  20. }
  21. }
  22. }
  23. }

2.外层的循环条件在内层代码控制

  1. //i=0
  2. //j=0
  3. //j=1
  4. private static void loop3() {
  5. boolean flag = true;
  6. for (int i = 0; i < 3 && flag; i++) {
  7. System.out.println("i=" + i);
  8. for (int j = 0; j < 3 && flag; j++) {
  9. System.out.println("j=" + j);
  10. if (j == 1) {
  11. flag = false;
  12. }
  13. }
  14. }
  15. }

3.异常

  1. //i=0
  2. //j=0
  3. //j=1
  4. //--------------
  5. private static void loop4() {
  6. try {
  7. for (int i = 0; i < 3; i++) {
  8. System.out.println("i=" + i);
  9. for (int j = 0; j < 3; j++) {
  10. System.out.println("j=" + j);
  11. if (j == 1) {
  12. throw new Exception();
  13. }
  14. }
  15. }
  16. } catch (Exception e) {
  17. System.out.println("--------------");
  18. }
  19. }

4.return

  1. //i=0
  2. //j=0
  3. //j=1
  4. private static void loop5() {
  5. for (int i = 0; i < 3; i++) {
  6. System.out.println("i=" + i);
  7. for (int j = 0; j < 3; j++) {
  8. System.out.println("j=" + j);
  9. if (j == 1) {
  10. return;
  11. }
  12. }
  13. }
  14. }