[Java基础] 流程控制结构
流程控制结构
-
if - else
private static String checkHeartBeats(int heatBeats) { if (heatBeats > 100) { return "too fast"; } else if (heatBeats >= 60) { return "normal"; } else { return "too slow"; } }
-
switch - case
private static String getApha(int month) { switch (month) { case 1: return "One"; case 2: return "Two"; case 3: return "Three"; case 4: return "Four"; default: return "Unknown"; } }
-
for
private static void forLoop() { for (int i = 0; i < 10; i++) { System.out.println(i); } }
-
while
private static void whileLoop(){ int i = 1; while (i<=10){ System.out.println(i); i++; } }
-
do while
private static void doWhileLoop() { int i = 1; do { System.out.println(i); i++; } while (i <= 50); }
-
嵌套循环
private static void mutilLoop() { for (int j = 1; j <= 5; j++) { for (int i = 1; i <= j; i++) { System.out.print('*'); } System.out.println(); } }
-
break - continue
break:结束当前循环
continue:跳出当次循环
private static void breakAndContinue() { for (int i = 1; i <= 10; i++) { if (i % 3 == 0) { continue; } if (i % 5 == 0) { break; } System.out.print(i); } }
-
label 标志 跳出多重循环
private static void breakAndContinue() { label: for (int j = 1; j <= 4; j++) { for (int i = 1; i <= 10; i++) { if (i % 5 == 0) { break label; } System.out.print(i); } System.out.println(); } }