教妹學(xué)Java:12張圖帶你徹底了解流程控制語句
同學(xué)們好啊,我是沉默王二,一枚沉默但有趣又帥氣的程序員(聽,是不是一種二哥賣瓜的趕腳)。又到了《教妹學(xué) Java》的時(shí)間,很開心,很期待,很舒適。這是《教妹學(xué) Java》專欄的第 13 篇文章,我們來談?wù)?ldquo;Java 中的流程控制語句”。
強(qiáng)調(diào)一下,《教妹學(xué) Java》面向的是零基礎(chǔ)的 Java 愛好者,我希望能幫助同學(xué)們輕松邁進(jìn)編程世界的大門,為后續(xù)的深入學(xué)習(xí)打下堅(jiān)實(shí)的基礎(chǔ)。
“二哥,流程控制語句都有哪些呢?”三妹的臉上泛著甜甜的笑容,她開始對(duì)接下來要學(xué)習(xí)的內(nèi)容充滿期待了,這正是我感到欣慰的地方。
“比如說 if-else、switch、for、while、do-while、return、break、continue 等等,接下來,我們一個(gè)個(gè)來了解下。”
01、if-else 相關(guān)
1)if 語句
if 語句的格式如下:
- if(布爾表達(dá)式){
- // 如果條件為 true,則執(zhí)行這塊代碼
- }
畫個(gè)流程圖表示一下:
來寫個(gè)示例:
- public class IfExample {
- public static void main(String[] args) {
- int age = 20;
- if (age < 30) {
- System.out.println("青春年華");
- }
- }
- }
輸出:
- 青春年華
2)if-else 語句
if-else 語句的格式如下:
- if(布爾表達(dá)式){
- // 條件為 true 時(shí)執(zhí)行的代碼塊
- }else{
- // 條件為 false 時(shí)執(zhí)行的代碼塊
- }
畫個(gè)流程圖表示一下:
來寫個(gè)示例:
- public class IfElseExample {
- public static void main(String[] args) {
- int age = 31;
- if (age < 30) {
- System.out.println("青春年華");
- } else {
- System.out.println("而立之年");
- }
- }
- }
輸出:
- 而立之年
除了這個(gè)例子之外,還有一個(gè)判斷閏年(被 4 整除但不能被 100 整除或者被 400 整除)的例子:
- public class LeapYear {
- public static void main(String[] args) {
- int year = 2020;
- if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
- System.out.println("閏年");
- } else {
- System.out.println("普通年份");
- }
- }
- }
輸出:
- 閏年
如果執(zhí)行語句比較簡單的話,可以使用三元運(yùn)算符來代替 if-else 語句,如果條件為 true,返回 ? 后面 : 前面的值;如果條件為 false,返回 : 后面的值。
- public class IfElseTernaryExample {
- public static void main(String[] args) {
- int num = 13;
- String result = (num % 2 == 0) ? "偶數(shù)" : "奇數(shù)";
- System.out.println(result);
- }
- }
輸出:
- 奇數(shù)
3)if-else-if 語句
if-else-if 語句的格式如下:
- if(條件1){
- // 條件1 為 true 時(shí)執(zhí)行的代碼
- }else if(條件2){
- // 條件2 為 true 時(shí)執(zhí)行的代碼
- }
- else if(條件3){
- // 條件3 為 true 時(shí)執(zhí)行的代碼
- }
- ...
- else{
- // 以上條件均為 false 時(shí)執(zhí)行的代碼
- }
畫個(gè)流程圖表示一下:
來寫個(gè)示例:
- public class IfElseIfExample {
- public static void main(String[] args) {
- int age = 31;
- if (age < 30) {
- System.out.println("青春年華");
- } else if (age >= 30 && age < 40 ) {
- System.out.println("而立之年");
- } else if (age >= 40 && age < 50 ) {
- System.out.println("不惑之年");
- } else {
- System.out.println("知天命");
- }
- }
- }
輸出:
- 而立之年
4)if 嵌套語句
if 嵌套語句的格式如下:
- if(外側(cè)條件){
- // 外側(cè)條件為 true 時(shí)執(zhí)行的代碼
- if(內(nèi)側(cè)條件){
- // 內(nèi)側(cè)條件為 true 時(shí)執(zhí)行的代碼
- }
- }
畫個(gè)流程圖表示一下:
來寫個(gè)示例:
- public class NestedIfExample {
- public static void main(String[] args) {
- int age = 20;
- boolean isGirl = true;
- if (age >= 20) {
- if (isGirl) {
- System.out.println("女生法定結(jié)婚年齡");
- }
- }
- }
- }
輸出:
- 女生法定結(jié)婚年齡
02、switch 語句
switch 語句用來判斷變量與多個(gè)值之間的相等性。變量的類型可以是 byte、short、int、long,或者對(duì)應(yīng)的包裝器類型 Byte、Short、Integer、Long,以及字符串和枚舉。
來看一下 switch 語句的格式:
- switch(變量) {
- case 可選值1:
- // 可選值1匹配后執(zhí)行的代碼;
- break; // 該關(guān)鍵字是可選項(xiàng)
- case 可選值2:
- // 可選值2匹配后執(zhí)行的代碼;
- break; // 該關(guān)鍵字是可選項(xiàng)
- ......
- default: // 該關(guān)鍵字是可選項(xiàng)
- // 所有可選值都不匹配后執(zhí)行的代碼
- }
- 變量可以有 1 個(gè)或者 N 個(gè)值。
- 值類型必須和變量類型是一致的,并且值是確定的。
- 值必須是唯一的,不能重復(fù),否則編譯會(huì)出錯(cuò)。
- break 關(guān)鍵字是可選的,如果沒有,則執(zhí)行下一個(gè) case,如果有,則跳出 switch 語句。
- default 關(guān)鍵字也是可選的。
畫個(gè)流程圖:
來個(gè)示例:
- public class Switch1 {
- public static void main(String[] args) {
- int age = 20;
- switch (age) {
- case 20 :
- System.out.println("上學(xué)");
- break;
- case 24 :
- System.out.println("蘇州工作");
- break;
- case 30 :
- System.out.println("洛陽工作");
- break;
- default:
- System.out.println("未知");
- break; // 可省略
- }
- }
- }
輸出:
- 上學(xué)
當(dāng)兩個(gè)值要執(zhí)行的代碼相同時(shí),可以把要執(zhí)行的代碼寫在下一個(gè) case 語句中,而上一個(gè) case 語句中什么也沒有,來看一下示例:
- public class Switch2 {
- public static void main(String[] args) {
- String name = "沉默王二";
- switch (name) {
- case "詹姆斯":
- System.out.println("籃球運(yùn)動(dòng)員");
- break;
- case "穆里尼奧":
- System.out.println("足球教練");
- break;
- case "沉默王二":
- case "沉默王三":
- System.out.println("乒乓球愛好者");
- break;
- default:
- throw new IllegalArgumentException(
- "名字沒有匹配項(xiàng)");
- }
- }
- }
輸出:
- 乒乓球愛好者
枚舉作為 switch 語句的變量也很常見,來看例子:
- public class SwitchEnumDemo {
- public enum PlayerTypes {
- TENNIS,
- FOOTBALL,
- BASKETBALL,
- UNKNOWN
- }
- public static void main(String[] args) {
- System.out.println(createPlayer(PlayerTypes.BASKETBALL));
- }
- private static String createPlayer(PlayerTypes playerType) {
- switch (playerType) {
- case TENNIS:
- return "網(wǎng)球運(yùn)動(dòng)員費(fèi)德勒";
- case FOOTBALL:
- return "足球運(yùn)動(dòng)員C羅";
- case BASKETBALL:
- return "籃球運(yùn)動(dòng)員詹姆斯";
- case UNKNOWN:
- throw new IllegalArgumentException("未知");
- default:
- throw new IllegalArgumentException(
- "運(yùn)動(dòng)員類型: " + playerType);
- }
- }
- }
輸出:
- 籃球運(yùn)動(dòng)員詹姆斯
03、for 循環(huán)
1)普通 for 循環(huán)
普通的 for 循環(huán)可以分為 4 個(gè)部分:
1)初始變量:循環(huán)開始執(zhí)行時(shí)的初始條件。
2)條件:循環(huán)每次執(zhí)行時(shí)要判斷的條件,如果為 true,就執(zhí)行循環(huán)體;如果為 false,就跳出循環(huán)。當(dāng)然了,條件是可選的,如果沒有條件,則會(huì)一直循環(huán)。
3)循環(huán)體:循環(huán)每次要執(zhí)行的代碼塊,直到條件變?yōu)?false。
4)自增/自減:初識(shí)變量變化的方式。
來看一下普通 for 循環(huán)的格式:
- for(初識(shí)變量;條件;自增/自減){
- // 循環(huán)體
- }
畫個(gè)流程圖:
來個(gè)示例:
- public class ForExample {
- public static void main(String[] args) {
- for (int i = 0; i < 5; i++) {
- System.out.println("沉默王三好美啊");
- }
- }
- }
輸出:
- 沉默王三好美啊
- 沉默王三好美啊
- 沉默王三好美啊
- 沉默王三好美啊
- 沉默王三好美啊
“哎呀,二哥,你真的是變著法夸我啊。”
“非也非也,三妹,你看不出我其實(shí)在夸我自己嗎?循環(huán)語句還可以嵌套呢,這樣就可以打印出更好玩的呢,你要不要看看?”
“好呀好呀!”
“看好了啊。”
- public class PyramidForExample {
- public static void main(String[] args) {
- for (int i = 0; i < 5; i++) {
- for (int j = 0;j<= i;j++) {
- System.out.print("❤");
- }
- System.out.println();
- }
- }
- }
打印出什么玩意呢?
- ❤
- ❤❤
- ❤❤❤
- ❤❤❤❤
- ❤❤❤❤❤
“哇,太不可思議了,二哥。”
“嘿嘿。”
2)for-each
for-each 循環(huán)通常用于遍歷數(shù)組和集合,它的使用規(guī)則比普通的 for 循環(huán)還要簡單,不需要初始變量,不需要條件,不需要下標(biāo)來自增或者自減。來看一下語法:
- for(元素類型 元素 : 數(shù)組或集合){
- // 要執(zhí)行的代碼
- }
來看一下示例:
- public class ForEachExample {
- public static void main(String[] args) {
- String[] strs = {"沉默王二", "一枚有趣的程序員"};
- for (String str : strs) {
- System.out.println(str);
- }
- }
- }
輸出:
- 沉默王二
- 一枚有趣的程序員
“呀,二哥,你開始王哥賣瓜了啊。”
“嘿嘿,三妹,你這樣說哥會(huì)臉紅的。”
3)無限 for 循環(huán)
“三妹,你想不想體驗(yàn)一下無限 for 循環(huán)的威力,也就是死循環(huán)。”
“二哥,那會(huì)有什么樣的后果啊?”
“來,看看就知道了。”
- public class InfinitiveForExample {
- public static void main(String[] args) {
- for(;;){
- System.out.println("停不下來。。。。");
- }
- }
- }
輸出:
- 停不下來。。。。
- 停不下來。。。。
- 停不下來。。。。
- 停不下來。。。。
一旦運(yùn)行起來,就停不下來了,除非強(qiáng)制停止。
04、while 循環(huán)
來看一下 while 循環(huán)的格式:
- while(條件){
- //循環(huán)體
- }
畫個(gè)流程圖:
來個(gè)示例:
- public class WhileExample {
- public static void main(String[] args) {
- int i = 0;
- while (true) {
- System.out.println("沉默王三");
- i++;
- if (i == 5) {
- break;
- }
- }
- }
- }
“三妹,你猜猜會(huì)輸出幾次?”
“五次嗎?”
“對(duì)了,你可真聰明。”
- 沉默王三
- 沉默王三
- 沉默王三
- 沉默王三
- 沉默王三
“三妹,你想不想體驗(yàn)一下無限 while 循環(huán)的威力,也就是死循環(huán)。”
“二哥,那會(huì)有什么樣的后果啊?”
“來,看看就知道了。”
- public class InfinitiveWhileExample {
- public static void main(String[] args) {
- while (true) {
- System.out.println("停不下來。。。。");
- }
- }
- }
輸出:
- 停不下來。。。。
- 停不下來。。。。
- 停不下來。。。。
- 停不下來。。。。
把 while 的條件設(shè)置為 true,并且循環(huán)體中沒有 break 關(guān)鍵字的話,程序一旦運(yùn)行起來,就根本停不下來了,除非強(qiáng)制停止。
05、do-while 循環(huán)
來看一下 do-while 循環(huán)的格式:
- do{
- // 循環(huán)體
- }while(提交);
畫個(gè)流程圖:
來個(gè)示例:
- public class DoWhileExample {
- public static void main(String[] args) {
- int i = 0;
- do {
- System.out.println("沉默王三");
- i++;
- if (i == 5) {
- break;
- }
- } while (true);
- }
- }
“三妹,你猜猜會(huì)輸出幾次?”
“五次嗎?”
“對(duì)了,你可真聰明。”
- 沉默王三
- 沉默王三
- 沉默王三
- 沉默王三
- 沉默王三
“三妹,你想不想體驗(yàn)一下無限 do-while 循環(huán)的威力......”
“二哥,又來啊,我都膩了。”
“來吧,例行公事,就假裝看看嘛。”
- public class InfinitiveDoWhileExample {
- public static void main(String[] args) {
- do {
- System.out.println("停不下來。。。。");
- } while (true);
- }
- }
輸出:
- 停不下來。。。。
- 停不下來。。。。
- 停不下來。。。。
- 停不下來。。。。
把 do-while 的條件設(shè)置為 true,并且循環(huán)體中沒有 break 關(guān)鍵字的話,程序一旦運(yùn)行起來,就根本停不下來了,除非強(qiáng)制停止。
06、break
break 關(guān)鍵字通常用于中斷循環(huán)或 switch 語句,它在指定條件下中斷程序的當(dāng)前流程。如果是內(nèi)部循環(huán),則僅中斷內(nèi)部循環(huán)。
可以將 break 關(guān)鍵字用于所有類型循環(huán)語句中,比如說 for 循環(huán)、while 循環(huán),以及 do-while 循環(huán)。
來畫個(gè)流程圖感受一下:
用在 for 循環(huán)中的示例:
- for (int i = 1; i <= 10; i++) {
- if (i == 5) {
- break;
- }
- System.out.println(i);
- }
用在嵌套 for 循環(huán)中的示例:
- for (int i = 1; i <= 3; i++) {
- for (int j = 1; j <= 3; j++) {
- if (i == 2 && j == 2) {
- break;
- }
- System.out.println(i + " " + j);
- }
- }
用在 while 循環(huán)中的示例:
- int i = 1;
- while (i <= 10) {
- if (i == 5) {
- i++;
- break;
- }
- System.out.println(i);
- i++;
- }
用在 do-while 循環(huán)中的示例:
- int j = 1;
- do {
- if (j == 5) {
- j++;
- break;
- }
- System.out.println(j);
- j++;
- } while (j <= 10);
用在 switch 語句中的示例:
- switch (age) {
- case 20 :
- System.out.println("上學(xué)");
- break;
- case 24 :
- System.out.println("蘇州工作");
- break;
- case 30 :
- System.out.println("洛陽工作");
- break;
- default:
- System.out.println("未知");
- break; // 可省略
- }
07、continue
當(dāng)我們需要在 for 循環(huán)或者 (do)while 循環(huán)中立即跳轉(zhuǎn)到下一個(gè)循環(huán)時(shí),就可以使用 continue 關(guān)鍵字,通常用于跳過指定條件下的循環(huán)體,如果循環(huán)是嵌套的,僅跳過當(dāng)前循環(huán)。
來個(gè)示例:
- public class ContinueDemo {
- public static void main(String[] args) {
- for (int i = 1; i <= 10; i++) {
- if (i == 5) {
- // 使用 continue 關(guān)鍵字
- continue;// 5 將會(huì)被跳過
- }
- System.out.println(i);
- }
- }
- }
輸出:
- 1
- 2
- 3
- 4
- 6
- 7
- 8
- 9
- 10
“二哥,5 真的被跳過了呀。”
“那必須滴。不然就是 bug。”
再來個(gè)循環(huán)嵌套的例子。
- public class ContinueInnerDemo {
- public static void main(String[] args) {
- for (int i = 1; i <= 3; i++) {
- for (int j = 1; j <= 3; j++) {
- if (i == 2 && j == 2) {
- // 當(dāng)i=2,j=2時(shí)跳過
- continue;
- }
- System.out.println(i + " " + j);
- }
- }
- }
- }
打印出什么玩意呢?
- 1 1
- 1 2
- 1 3
- 2 1
- 2 3
- 3 1
- 3 2
- 3 3
“2 2” 沒有輸出,被跳過了。
再來看一下 while 循環(huán)時(shí) continue 的使用示例:
- public class ContinueWhileDemo {
- public static void main(String[] args) {
- int i = 1;
- while (i <= 10) {
- if (i == 5) {
- i++;
- continue;
- }
- System.out.println(i);
- i++;
- }
- }
- }
輸出:
- 1
- 2
- 3
- 4
- 6
- 7
- 8
- 9
- 10
注意:如果把 if 條件中的“i++”省略掉的話,程序就會(huì)進(jìn)入死循環(huán),一直在 continue。
最后,再來看一下 do-while 循環(huán)時(shí) continue 的使用示例:
- public class ContinueDoWhileDemo {
- public static void main(String[] args) {
- int i=1;
- do{
- if(i==5){
- i++;
- continue;
- }
- System.out.println(i);
- i++;
- }while(i<=10);
- }
- }
輸出:
- 1
- 2
- 3
- 4
- 6
- 7
- 8
- 9
- 10
注意:同樣的,如果把 if 條件中的“i++”省略掉的話,程序就會(huì)進(jìn)入死循環(huán),一直在 continue。
“好了,三妹,關(guān)于 Java 中的流程控制語句就先說這么多吧。”轉(zhuǎn)動(dòng)了一下僵硬的脖子后,我對(duì)三妹說。
“二哥,你辛苦了,容我好好消化一下。”
本文轉(zhuǎn)載自微信公眾號(hào)「沉默王二」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系沉默王二公眾號(hào)。