1 package com.jdk7.chapter1; 2 3 public class ControlFollow { 4 public static int number = 10; 5 6 /** 7 * if控制语句 8 * @param n 9 */ 10 public void ifStatement(int n){ 11 System.out.print(n+" "); 12 if(n==number){ 13 System.out.println(); 14 }else if(n>number){ 15 this.ifStatement(--n); 16 }else{ 17 this.ifStatement(++n); 18 } 19 } 20 /* 21 执行结果: 22 if控制语句 23 20 19 18 17 16 15 14 13 12 11 10 24 10 25 1 2 3 4 5 6 7 8 9 10 26 */ 27 28 /** 29 * for控制语句 30 * @param n 31 */ 32 public void forStatement(int n){ 33 for(;n<number;n++){ 34 System.out.print(n+" "); 35 } 36 for(;n>number;n--){ 37 System.out.print(n+" "); 38 } 39 System.out.println("n : "+n); 40 } 41 /* 42 执行结果: 43 for控制语句 44 20 19 18 17 16 15 14 13 12 11 n : 10 45 n : 10 46 1 2 3 4 5 6 7 8 9 n : 10 47 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 n : 10 48 */ 49 50 /** 51 * while控制语句 52 * @param n 53 */ 54 public void whileStatement(int n){ 55 while(n>number){ 56 System.out.print(n--+" "); 57 } 58 while(n<number){ 59 System.out.print(n+++" "); 60 } 61 System.out.println(n); 62 } 63 /* 64 执行结果: 65 while控制语句 66 20 19 18 17 16 15 14 13 12 11 10 67 10 68 1 2 3 4 5 6 7 8 9 10 69 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 70 */ 71 72 /** 73 * do...while控制语句 74 * @param n 75 */ 76 public void doWhileStatement(int n){ 77 if(n>number){ 78 do{ 79 System.out.print(n--+" "); 80 }while(n>number); 81 }else if(n<number){ 82 do{ 83 System.out.print(n+++" "); 84 }while(n<number); 85 } 86 System.out.println(n); 87 } 88 /* 89 执行结果: 90 do...while控制语句 91 20 19 18 17 16 15 14 13 12 11 10 92 10 93 1 2 3 4 5 6 7 8 9 10 94 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10 95 */ 96 97 /** 98 * switch控制语句 99 * @param n 100 */ 101 public void switchStatement(int n){ 102 switch(n){ 103 case 11: 104 System.out.println("n = 11"); 105 break; 106 case 10: 107 System.out.println("n = 10"); 108 break; 109 case 9: 110 System.out.println("n = 9"); 111 break; 112 default: 113 System.out.println("n不是11、10、9"); 114 } 115 /* 116 执行结果: 117 switch控制语句 118 n = 11 119 n = 10 120 n = 9 121 n不是11、10、9 122 */ 123 124 } 125 public static void main(String[] args) { 126 ControlFollow cf = new ControlFollow(); 127 System.out.println("if控制语句"); 128 cf.ifStatement(20); 129 cf.ifStatement(10); 130 cf.ifStatement(1); 131 System.out.println("for控制语句"); 132 cf.forStatement(20); 133 cf.forStatement(10); 134 cf.forStatement(1); 135 cf.forStatement(-3); 136 System.out.println("while控制语句"); 137 cf.whileStatement(20); 138 cf.whileStatement(10); 139 cf.whileStatement(1); 140 cf.whileStatement(-3); 141 System.out.println("do...while控制语句"); 142 cf.doWhileStatement(20); 143 cf.doWhileStatement(10); 144 cf.doWhileStatement(1); 145 cf.doWhileStatement(-3); 146 System.out.println("switch控制语句"); 147 cf.switchStatement(11); 148 cf.switchStatement(10); 149 cf.switchStatement(9); 150 cf.switchStatement(20); 151 152 153 154 } 155 156 }