天天看點

JAVA語言文法_流程控制(part3)

文章目錄

      • JAVA語言文法
        • 三、流程控制
          • 1、程式流程控制概述
          • 2、順序結構
          • 3、分支結構
          • 4、分支結構語句練習
          • 5、加深鍵盤類Scanner類的使用
          • 6、分支結構語句練習2
          • 7、分支結構&switch分支
          • 8、循環結構& for 循環(重點)
          • 9、循環結構&for循環練習
          • 10、循環結構&while循環
          • 11、循環結構&do-while循環
          • 12、循環結構&關鍵字break
          • 13、循環結構&關鍵字continue
          • 14、循環結構&關鍵字return
          • 15、循環結構&嵌套循環(多重循環)
          • 16、循環結構&嵌套循環練習1
          • 17、循環結構&嵌套循環練習2

JAVA語言文法

三、流程控制

1、程式流程控制概述

​ 流程控制語句是用來控制程式中各語句執行順序的語句,可以把語句組合成能完成一定給功能的小邏輯子產品。

​ 其流程控制方式采用結構化程式設計中規定的三種基本流程結構,即:

(1)、順序結構 : 程式從上到下逐行地執行,中間沒有任何判斷和跳轉。

​	(2)、分支結構 : 
		  根據條件,選擇性地執行某段代碼
		  有if、if-else、if-else if..else和switch-case的兩種分支語句。

​	(3)、循環結構
		  根據循環條件,重複性地執行某段代碼;
		  有while、do-while、for三種循環語句;
		  注意: JDK1.5開始提供了foreach的循環, 友善周遊集合、數組元素。
           
2、順序結構
JAVA語言文法_流程控制(part3)
3、分支結構

​ (1)、分支語句 if

JAVA語言文法_流程控制(part3)

​ (2)、分支語句 if-else

JAVA語言文法_流程控制(part3)

​ (3)、分支語句 if else if …else

JAVA語言文法_流程控制(part3)

if -else 使用說明:

(1)、條件表達式必須是布爾表達式(關系表達式或者邏輯表達式)、布爾變量;
(2)、語句塊隻有一條執行語句時,一隊花括号{}可以省略,但是建議保留;
(3)、if-else語句結構,根據需要可以嵌套使用;
(4)、當if-else結構是“多選一”時,最後的else是可選的,根據需要可以省略;
(5)、當多個條件是“互斥”關系時,條件判斷語句以及執行語句間順序是無所謂的; 當多個條件是“包含”關系時,可遵循“小上大下/子上父下” (即是範圍小的聲明在範圍大的上面)。
           
4、分支結構語句練習

代碼示範:

package com.rucoding.d5;

/**
 * @author LiuYiXin
 *
 */
public class IfelseDemo01 {
	public static void main(String[] args) {
		/*
		 * 第一種:
		 * if(條件表達式){
		 * 	執行表達式
		 * }
		 * 
		 * 第二種:
		 * if(條件表達式){
		 * 	執行表達式1
		 * }else{
		 * 	執行表達式2
		 * }
		 * 
		 * 第三種:
		 * if(條件表達式1){
		 * 	執行表達式1
		 * }else if(條件表達式2){
		 * 	執行表達式2
		 * }else if(條件表達式3){
		 * 	執行表達式3
		 * }
		 * ...
		 * else{
		 * 	執行表達式n
		 * }
		 * 
		 */
		
		//舉例1 if語句
		int heartBeats = 179;
		if(heartBeats < 60 || heartBeats > 100){
			System.out.println("需要進一步做檢查");
		}
		System.out.println("檢查結束");
		
		//舉例2 if-else語句
		int age = 23;
		if(age < 18){
			System.out.println("你還未成年呢");
		}else{
			System.out.println("你是成年人了");
		}
		
		//舉例3 if else-if ...else 語句
		if(age < 0){
			System.out.println("資料有誤");
		}else if(age < 18){
			System.out.println("你還是青少年呢");
		}else if(age < 35){
			System.out.println("你是青壯年呢");
		}else if(age < 60){
			System.out.println("你是中年人了");
		}else if(age < 120){
			System.out.println("你已進入老年人生活啦");
		}else{ //根據實際的場景,這裡的else是可以去除的。
			System.out.println("你比烏龜還牛。。。");
		}
		
	}
}
           
5、加深鍵盤類Scanner類的使用

​ 場景模拟:假如需要擷取鍵盤的輸入,此時需要從鍵盤擷取不同類型的資料類型,需要使用到Scanner類。

具體步驟:
1.檢視API文檔;
2.需要導入包: import java.util.Scanner;
3.Scanner的執行個體化;
4.調用Scanner類的相關方法, 來擷取指定的變量。
           

代碼示範:

這裡有個疑問:每次運作輸出sout語句,光标不能直接換行的喲。能解不?

package com.rucoding.d5;

import java.util.Scanner;

/**
 * @author LiuYiXin
 *
 */
public class ScannerDemo01 {
	public static void main(String[] args) {
		//聲明一個Scanner類
		Scanner scanner = new Scanner(System.in);
		System.out.println("請輸入你的幸運數字: ");
		int i = scanner.nextInt();//nextInt()方法接收的是數字類型
		System.out.println("你輸入的幸運數字為:" + i);
		
		//錄入大一新生的基本資訊
		System.out.println("請輸入你的姓名:");
		String stuName = scanner.next();
		System.out.println("你輸入的姓名為:" + stuName);
		
		System.out.println("請輸入你的年齡:");
		int stuAge = scanner.nextInt();
		System.out.println("你輸入的年齡為:" + stuAge);
		
		System.out.println("請輸入你的體重:");
		double stuWeight = scanner.nextDouble();
		System.out.println("你輸入的體重為:" + stuWeight);
		
		System.out.println("請選擇你單身與否?(true(是)/false(否))");
		boolean stuIsSingle = scanner.nextBoolean();
		System.out.println("你選擇的是:" +stuIsSingle);
		
		//char類型的擷取, Scanner類沒有提供相應的方法, 隻能擷取一個字元串
		System.out.println("請輸入你的性别:(男/女)");
		String stuSex = scanner.next();
		char stuGender = stuSex.charAt(0);
		System.out.println("你輸入的性别屬性為:" + stuGender);
	}
}
           
6、分支結構語句練習2

代碼示範1:

package com.rucoding.d5;

import java.util.Scanner;

/**
 * @author LiuYiXin
 *
 */
public class IfelseDemo02 {
	public static void main(String[] args) {
		//分支結構語句if else-if else的練習
		/*
		嶽小鵬參加數學考試,他和父親嶽不群達成承諾:
		如果:成績為100分時,獎勵一輛BMW;
		成績為(80,99]時,獎勵一台iphone xs max;
		當成績為[60,80]時,獎勵一個 iPad;
		其它時,什麼獎勵也沒有。
		請從鍵盤輸入嶽小鵬的期末成績,并加以判斷
		*/
		
		//聲明Scanner類
		Scanner scanner = new Scanner(System.in); //接收鍵盤的輸入System.in
		System.out.println("請輸入嶽小鵬的數學成績:");
		int stuScore = scanner.nextInt();
		
		if(stuScore == 100){
			System.out.println("嶽小鵬的數學成績為:" + stuScore + ",獎勵一輛BMW");
		}else if(stuScore > 80 && stuScore <= 99){
			System.out.println("嶽小鵬的數學成績為:" + stuScore + ",獎勵一台iphone xs max");
		}else if(stuScore >= 60 && stuScore <= 80){
			System.out.println("嶽小鵬的數學成績為:" + stuScore + ",獎勵一個iPad");
		}else if(stuScore < 0 || stuScore > 100){
			System.out.println("輸入的數字有誤,請檢查!");
		}else{
			System.out.println("不及格, 什麼獎勵也沒有");
		}
		
		
	}
}
           
7、分支結構&switch分支

switch - case 結構:

JAVA語言文法_流程控制(part3)
注意:
switch-case 結構中的表達式, 隻能是如下的六種資料類型之一: byte、short、char、int、枚舉類型(JDK5.0)、String類型(JDK7.0)
不能是: boolean、long、float、double類型。
           

溫馨Tip:以下練習題目,可自由安排時間,比如是每日一題,練練手。

練習1代碼示範:

package com.rucoding.d5;

/**
 * @author LiuYiXin
 *
 */
public class SwitchCaseDemo01 {
	public static void main(String[] args) {
		//分支結構之二: switch-case結構
		/*
		 * 格式定義:
		 * switch(表達式){
		 * case 常量1:
		 * 		執行語句1;
		 * 		//break;
		 * case 常量2:
		 * 		執行語句2;
		 * 		//break;
		 * ...
		 * default:
		 * 		執行語句n;
		 * 		break;
		 * }
		 */
		
		
		//說明:
		//①.根據switch表達式的值, 依次比對各個case的值,一旦比對成功,則進入對應的case語句,執行相關語句。
		//②.當調用完執行的語句後,則仍然繼續向下執行其他的case語句,直到遇見break關鍵字或末尾結束為止。
		//③.break關鍵字,可以使用在switch-case語句中,表示一旦執行遇到該關鍵字,就會跳出switch-case結構。
		//④.switch-case 結構中的表達式, 隻能是如下的六種資料類型之一: byte、short、char、int、枚舉類型(JDK5.0)、String類型(JDK7.0)! 不能是: boolean、long、float、double類型
		//⑤.case之後聲明的是常量,不能聲明範圍。
		//⑥.break關鍵字是可選的。
		//⑦.default:相當于if-else的else default結構是可選的,而且位置是靈活的。
		
		//switch-case可以接受的表達式 int類型
		int num = 2;
		switch(num){
		case 0:
			System.out.println("Zero");
		case 1:
			System.out.println("One");
		case 2:
			System.out.println("Two");
			break;//此處如果不加break,那麼遇到case 2執行的時候,會繼續執行其他case語句,直到遇見break或者末尾位元組結束才會跳出
		case 3:
			System.out.println("Three");
			break;
		case 4:
			System.out.println("Four");
			break;
		case 5:
			System.out.println("Five");
			break;
		default:
			System.out.println("Other...");
			break;
		}
		
		//switch-case不能接收的表達式類型,比如boolean類型。
		boolean isOk = true;
		switch(isOk){ //無法接收boolean類型的表達式 ,無法通過編譯。
		case true:
			System.out.println("Ok");
			break;
		case false:
			System.out.println("Not Ok");
			break;
		default:
			System.out.println("資訊有誤!");
			break;
		}
		
		//String類型的,自從jdk1.7開始
		String season = "spring";
		switch(season){
		case "spring":
			System.out.println("春暖花開");
			break;
		case "summer":
			System.out.println("夏日炎炎");
			break;
		case "autumn":
			System.out.println("秋高氣爽");
			break;
		case "winter":
			System.out.println("白雪皚皚");
			break;
		default:
			System.out.println("輸入有誤!");
			break;
		}
		
		
	}
}
           

​ 練習2代碼示範:

package com.rucoding.d5;

import java.util.Scanner;

/**
 * @author LiuYiXin
 *
 */
public class SwitchCaseDemo02 {
	public static void main(String[] args) {
		/*
		使用switch 把小寫類型的char型轉為大寫。隻轉換a, b, c, d, e. 其它的輸出“other”。
		提示:String word = scan.next();  char c = word.charAt(0); switch(c){}
		*/
		
		//聲明Scanner類
		Scanner scanner = new Scanner(System.in);
		System.out.println("輸入小寫的字母,會自動轉為大寫:");
		String str = scanner.next();
		char lowerWord = str.charAt(0);//擷取指定索引位置的值
		//
		switch(lowerWord){
		case 'a':
			System.out.println("A");
			break;
		case 'b':
			System.out.println("B");
			break;
		case 'c':
			System.out.println("C");
			break;
		case 'd':
			System.out.println("D");
			break;
		case 'e':
			System.out.println("E");
			break;
		default:
			System.out.println("other...");
			break;
		}
		
	}
}
           

練習3代碼示範:

package com.rucoding.d5;

/**
 * @author LiuYiXin
 *
 */
public class SwitchCaseDemo03 {
	public static void main(String[] args) {
		/*
		對學生成績大于60分的,輸出“合格”。低于60分的,輸出“不合格”。

		說明:如果switch-case語句中多個相同語句,可以進行合并。
		*/
		int stuScore = 78;
		switch(stuScore / 10){
		case 0: //switch-case語句中執行多個相同的語句,可以進行合并操作
		case 1:
		case 2:
		case 3:
		case 4:
		case 5:
			System.out.println("不合格");
			break;
		case 6:
		case 7:
		case 8:
		case 9:
		case 10:
			System.out.println("合格");
			break;
		default:
			System.out.println("輸入有誤");
			break;
		}
		
		//優化上述,更優解
		switch(stuScore / 60){
		case 0:
			System.out.println("不合格");
			break;
		case 1:
			System.out.println("合格");
			break;
		default:
			System.out.println("輸入有誤!");
			break;
		}
		
	}
}

           

練習4代碼示範:

*/
//利用分支結構switch-case實作
int month = 10;
switch(month){
case 3:
case 4:
case 5:
	System.out.println("春季");
	break;
case 6:
case 7:
case 8:
	System.out.println("夏季");
	break;
case 9:
case 10:
case 11:
	System.out.println("秋季");
	break;
case 12:
case 1:
case 2:
	System.out.println("冬季");
	break;
default:
	System.out.println("輸入月份有誤");
	break;
}
           

練習5代碼示範:

package com.rucoding.d6;

import java.util.Scanner;

/**
 * @author LiuYiXin
 *
 */
public class SwitchCaseDemo01 {
	public static void main(String[] args) {
		/*
		編寫程式:從鍵盤上輸入2019年的"month"和"day",
		要求通過程式輸出 輸入的日期為2019年的第幾天。
		比如2 月 15 日 : 31 + 15 即是1月31天 + 15

		5 7: 31 + 28 +31 +30 + 7
		...
		說明:break在switch-case中是可選的。
		*/

		//聲明從鍵盤接收的Scanner類
		Scanner scanner = new Scanner(System.in);
		System.out.println("請輸入合法月份month: ");
		int month = scanner.nextInt();
		System.out.println("請輸入合法日期day: ");
		int day = scanner.nextInt();
		
		//定義總變量天數
		int sumDays = 0;
		switch(month){
//		case 1:
//			sumDays = day;
//			break;
//		case 2:
//			sumDays = 31 + day;
//			break;
//		case 3:
//			sumDays = 31 + 28 + day;  
//		case 4:
//			sumDays = 31 + 28 + 31 + day;寫着寫着發現太備援了,很多都是重複的代碼 31 + .. day 一直都在,優化一下
		//我們倒着寫
		case 12:
			sumDays += 30;
		case 11:
			sumDays += 31;
		case 10:
			sumDays += 30;
		case 9:
			sumDays += 31;
		case 8:
			sumDays += 31;
		case 7:
			sumDays += 30;
		case 6:
			sumDays += 31;
		case 5:
			sumDays += 30;
		case 4:
			sumDays += 31;
		case 3:
			sumDays += 28;
		case 2:
			sumDays += 31;
		case 1:
			sumDays += day;
		
		}	
		System.out.println("2019年的" + month + "月" + day + "日是第2019年" + sumDays + "天");
		
		
	}
}
           

練習5代碼示範(更新版):

package com.rucoding.d6;

import java.util.Scanner;

/**
 * @author LiuYiXin
 *
 */
public class SwitchCaseDemo02 {
	public static void main(String[] args) {
		/*
		從鍵盤分别輸入年、月、日,判斷這一天是當年的第幾天
		注:判斷一年是否是閏年的标準:
		1)可以被4 整除,但是不能被100整除;   【判斷方法一】
		2)可以被400整除。    【或者直接能被400整除 判斷方法二】
		
		翻譯成計算機能聽懂的語言:
		((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))

		說明:
		1凡是可以使用switch-case的結構,都可以轉換為if-else。反之,不成立。
		2.我們寫分支結構時,當發現既可以使用switch-case,
		(同時,switch中表達式的取值情況不太多),
		又可以使用,我們優先選擇使用switch-case。原因:switch-case執行效率稍高。
		*/
		
		//這題是上面練習4的更新, 多了一個年份, 改變了 2月的天數,閏年的2月是29天,平年的2月是28天
		
		//聲明一個接收鍵盤輸入的Scanner類
		Scanner scanner = new Scanner(System.in);
		System.out.println("請輸入合法的年份Year:");
		int year = scanner.nextInt();
		System.out.println("請輸入合法的年份Month:");
		int month = scanner.nextInt();
		System.out.println("請輸入合法的年份Day:");
		int day = scanner.nextInt();
		
		//定義變量 ,總天數
		int sumDays = 0;
		
		switch(month){
		case 12:
			sumDays += 30;
		case 11:
			sumDays += 31;
		case 10:
			sumDays += 30;
		case 9:
			sumDays += 31;
		case 8:
			sumDays += 31;
		case 7:
			sumDays += 30;
		case 6:
			sumDays += 31;
		case 5:
			sumDays += 30;
		case 4:
			sumDays += 31;
		case 3:
			//判斷輸入的year年份是否為閏年
			if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)){
				sumDays += 29;
			}else{
				sumDays += 28;
			}
		case 2:
			sumDays +=31;
		case 1:
			sumDays += day;
		}
			
		System.out.println(year + "年的" + month + "月" + day + "日是第" + year + "年" + sumDays + "天");

	}
}
           

練習6代碼示範:

package com.rucoding.d6;

import java.util.Scanner;

/**
 * @author LiuYiXin
 *
 */
public class SwitchCaseDemo03 {
	public static void main(String[] args) {
		/*
		編寫一個程式,為一個給定的年份找出其對應的中國生肖。
		中國的生肖基于12年一個周期,每年用一個動物代表:
		
		十二生肖速算法:出生的年份除以12 ,取餘數,如果能整除,餘數視為0
		按照下列餘數數字對應生肖動物
		0-猴 1-雞 2-狗 3-豬 4-鼠 5-牛 6-虎 7-兔  8-龍  9-蛇  10-馬  11-羊
		
		比如:2019年: 2019 % 12 == 3(餘數) ,即是生肖為 豬 
		*/
		
		//聲明一個鍵盤接收Scanner類
		Scanner scanner = new Scanner(System.in);
		System.out.println("請輸入你的誕生年份year: ");
		int year = scanner.nextInt();
		
		//除以12,取餘變量
		int num = year % 12;
		switch(num){
		case 0:
			System.out.println("你的生肖為猴");
			break;
		case 1:
			System.out.println("你的生肖為雞");
			break;
		case 2:
			System.out.println("你的生肖為狗");
			break;
		case 3:
			System.out.println("你的生肖為豬");
			break;
		case 4:
			System.out.println("你的生肖為鼠");
			break;
		case 5:
			System.out.println("你的生肖為牛");
			break;
		case 6:
			System.out.println("你的生肖為虎");
			break;
		case 7:
			System.out.println("你的生肖為兔");
			break;
		case 8:
			System.out.println("你的生肖為龍");
			break;
		case 9:
			System.out.println("你的生肖為蛇");
			break;
		case 10:
			System.out.println("你的生肖為馬");
			break;
		case 11:
			System.out.println("你的生肖為羊");
			break;
		default:
			System.out.println("輸入資訊有誤!");
			break;
		}
		
	}
}	
           
8、循環結構& for 循環(重點)

​ 循環結構描述: 在某些條件滿足的條件下,反複執行特定代碼的功能。

​ 循環結構的分類:

​ (1)、for循環

​ (2)、while循環

​ (3)、do-while循環

JAVA語言文法_流程控制(part3)

舉例圖解:

JAVA語言文法_流程控制(part3)
9、循環結構&for循環練習

溫馨Tip:以下練習題目,可自由安排時間,比如是每日一題,練練手。

練習1代碼示範:

package com.rucoding.d5;

/**
 * @author LiuYiXin
 *
 */
public class ForDemo01 {
	public static void main(String[] args) {
		//for循環
		/*
		 * for的文法格式
		 * for(①初始化部分;②循環條件部分;④疊代部分){
		 * 		③.循環體部分;
		 * }
		 * 
		 * 執行過程: ①-②-③-④-②-③-④-②-③-④...
		*/
		//for循環結構的使用:基本要素:①.初始化條件;②.循環條件;③.循環體部分;④.疊代條件部分。
		/*結構
		 * for(①;②;④){
		 * 		③
		 * }
		 */
		
		for(int i=1;i <= 5;i++){
			System.out.println("HelloWorld");
		}
		
		//練習
		int num = 1;
		for(System.out.print('a');num <= 3;System.out.print('c'),num++){
			System.out.print('b'); //輸出結果 abcbcbc
		}
		
		System.out.println(); 
		
		//練習2
		//周遊100以内的偶數,擷取所有偶數的和,輸出偶數的個數
		int sum = 0;
		int count = 0;
		for(int i=1;i <= 100;i++){
			if(i % 2 == 0){
				System.out.println(i);
				sum += i;
				count++;
			}
		}
		System.out.println("偶數總數和: " + sum + ",偶數個數:" + count);
		
	}
}

           

練習2代碼示範:

package com.rucoding.d5;

/**
 * @author LiuYiXin
 *
 */
public class ForDemo02 {
	/*
	編寫程式從1循環到150,并在每行列印一個值,
	另外在每個3的倍數行上列印出“foo”,
	在每個5的倍數行上列印“biz”,
	在每個7的倍數行上列印輸出“baz”。
	*/
	
	public static void main(String[] args) {
		for(int i=1;i <= 150;i++){
			System.out.print(i + " ");
			if(i % 3 == 0){
				System.out.print("foo" + " ");  //不換行
			}
			
			if(i % 5 == 0){
				System.out.print("biz" + " ");
			}
			
			if(i % 7 == 0){
				System.out.print("baz");
			}
			System.out.println();  //周遊完一個數,列印換行操作
		}
	}
}

           

練習3代碼示範:

package com.rucoding.d6;

import java.util.Scanner;

/**
 * @author LiuYiXin
 *
 */
public class ForDemo01 {
	public static void main(String[] args) {
		/*
		輸入兩個正整數m和n,求其最大公約數和最小公倍數。
		比如:12和20的最大公約數是4,最小公倍數是60。
		說明:break關鍵字的使用
		*/
		
		// 分析一下:
		//12的約數,1 、2、3、4、6、12  (限制就是能被整除的)
		//20的約數,1、2、4、5、10、20  
		//此時最大的公約數肯定不會超過 最小數那個,即12
		
		//聲明一個鍵盤的接收類Scanner
		Scanner scanner = new Scanner(System.in);
		System.out.println("請輸入合法的正整數m: ");
		int m = scanner.nextInt();
		System.out.println("請輸入合法的正整數n: ");
		int n = scanner.nextInt();
		
		//求最大公約數
		//判斷兩個數的最小值
		int min = (m < n) ? m : n; //循環條件部分
		for(int i=min;i >=1;i--){ //最大不會超過最小那個12,從12開始遞減取最大的
			if(m % i == 0 && n % i == 0){
				System.out.println(m + "和" + n + "的最大公約數為:" +  i);
				break;
			}
		}
		
		//求兩個數的最小公倍數
		//分析一下:
		//12和20 的公倍數,範圍最大在他們倆的乘積 m*n 即是 12*20 = 240,最小的範圍大于最大那個值
		
		//判斷兩個數的最大值
		int max = (m > n) ? m : n;
		
		for(int i=max;i <= m*n;i++){  //循環條件部分
			if(i % m == 0 && i % n == 0){
				System.out.println("最小的公倍數為:" + i);
				break;
			}
		}
		
	}
}
           

練習4代碼示範:

package com.rucoding.d6;

/**
 * @author LiuYiXin
 *
 */
public class ForDemo02 {
	/*
	輸出所有的水仙花數,所謂水仙花數是指一個3位數,其各個位上數字立方和等于其本身。
	例如:153 = 1*1*1 + 3*3*3 + 5*5*5

	*/
	public static void main(String[] args) {
		//拆解,先取這個數個位、十位、百位
		for(int i=100;i <=999;i++){
			int ge = i % 10; //個位
			int shi = i % 100 / 10; //十位
			int bai = i / 100; //百位
//			int result = ge^3 + shi^3 + bai^3; //a^3這樣可不行, java中的^符号是來表示"異或" 運算的。
			int result = ge*ge*ge + shi*shi*shi + bai*bai*bai;
			if(i == result){
				System.out.println("水仙花數是:" + i);
			}
		
		}
		
	}
}
           
10、循環結構&while循環
基本文法格式:
①.初始化部分
while(②循環條件部分){
	③.循環體部分;
	④.疊代部分;
}

執行過程描述: ①-②-③-④-②-③-④-...②-③-④

說明:
(1)、注意不要忘記聲明④疊代部分。否則,循環将不能結束,進入死循環。
(2)、for循環和while循環可以互相轉換的。
           

代碼示範:

package com.rucoding.d5;

/**
 * @author LiuYiXin
 *
 */
public class WhileDemo01 {
	
	/*
	 * while循環結構的使用:
	 * 基本要素:
	 * ①.初始化條件
	 * ②.循環條件
	 * ③.循環體部分
	 * ④.疊代條件
	 * 
	 * 結構:
	 * ①.初始化部分
	 * while(②.循環條件部分){
	 * 		③.循環體部分;
	 * 		④.疊代部分;
	 * }
	 * 
	 * 執行過程描述: ①-②-③-④-②-③-④-...②-③-④
	 * 
	 * 說明:
	 * 1、寫while循環的,記得别丢了疊代條件,一旦丢失,可能會導緻死循環
	 * 2、寫程式避免死循環
	 * 3、while循環和for循環可以互相轉換。
	 * 
	 * 差別: for循環和while循環的初始化條件部分的作用範圍不同。
	 */
	
	
	//周遊100以内的偶數,擷取所有偶數的和,輸出偶數的個數
	public static void main(String[] args) {
		//改用while循環實作
		int sum =0;
		int count =0;
		int i = 1;
		while(i <= 100){
			if(i % 2 == 0){
				System.out.println(i);
				sum += i;
				count++;
			}
			i++;
		}
		System.out.println("偶數總和為:" + sum + ",偶數個數為:" + count);
	}
}
           
11、循環結構&do-while循環

​ 文法格式說明:

JAVA語言文法_流程控制(part3)

代碼示範:

package com.rucoding.d5;

/**
 * @author LiuYiXin
 *
 */
public class DoWhileDemo01 {
	/*
	 * do-while循環結構的使用
	 * 基本要素:
	 * ①.初始化條件
	 * ②.循環條件 ---> 是boolean類型
	 * ③.循環體
	 * ④.疊代條件
	 * 
	 * 結構:
	 * ①.初始化條件
	 * do{
	 * 		③.循環體部分
	 * 		④.疊代部分
	 * }while(②.循環條件部分);
	 * 
	 * 說明:do-while循環至少會執行一次循環體
	 */
	
	public static void main(String[] args) {
		//周遊100以内的所有偶數,并計算所有偶數的和和偶數的個數
		int sum =0;
		int count =0;
		int i = 1;
		do{
			if(i % 2 == 0){
				System.out.println(i);	
				sum +=i;
				count++;
			}
			i++;
		}while(i <= 100);
		System.out.println("偶數總和為:" + sum + ",偶數個數為:" + count);
		
		
		System.out.println("=======================");
		int numb = 10; //這裡改為12,輸出的結果數是一樣的(當滿足條件運作,輸出結果數一緻)
		while(numb > 10){
			System.out.println("while...");
			numb--;
		}
		
		int numb2 = 10;//這裡改為12,輸出的是一樣的(當滿足條件運作,輸出結果數一緻)
		do{
			System.out.println("do-while...");
			numb2--;
		}while(numb2 > 10);
		
	}
}
           
12、循環結構&關鍵字break
(1)、break的使用
break語句會終止某個語句塊的執行
{    
	......
	break;
	......
}
(2)、break語句出現在多層嵌套的語句塊中的時候,可以通過标簽指明要終止的是哪一層的語句塊
label1:	{	......
label2:		{	......
label3:			{	......
					break label2;
					......
				}
			}
		}
           

代碼示範(break的 “終止” 特征):

package com.rucoding.d5;

import java.util.Scanner;

/**
 * @author LiuYiXin
 *
 */
public class BreakDemo01 {
	//break關鍵字的作用: 出現break的時候,會跳出整個循環體
	/*
	 * 練習
	從鍵盤讀入個數不确定的整數,并判斷讀入的正數和負數的個數,輸入為0時結束程式。

	說明:
	1.不在循環條件部分限制次數的結構:while(true) , for(;;)
	2.結束循環的幾種方式:
		方式一:循環條件部分傳回false;
		方式二:在循環體中,執行break;
	*/
	public static void main(String[] args) {
		//聲明Scanner類
		Scanner scanner = new Scanner(System.in);
		int numZ = 0;
		int numF = 0;
		//while循環實作
		while(true){
			System.out.println("請輸入合法的整數:");
			int num = scanner.nextInt();
			if(num > 0){
				numZ++;
			}else if(num < 0){
				numF++;
			}else{
				break;//跳出整個循環
			}
		}
		System.out.println("輸入的正數個數為:" + numZ + ",輸入的負數的個數為:" + numF);
		
		
		//for循環實作
		for(;;){
			System.out.println("請輸入合法的整數:");
			int num = scanner.nextInt();
			if(num > 0){
				numZ++;
			}else if(num < 0){
				numF++;
			}else{
				break;//跳出整個循環
			}
		}
		System.out.println("輸入的正數個數為:" + numZ + ",輸入的負數的個數為:" + numF);
		
	}

}
           

代碼示範(break的 “标簽label終止” 特征):

package com.rucoding.d6;

/**
 * @author LiuYiXin
 *
 */
public class BreakLableDemo01 {
	public static void main(String[] args) {
		//示範一下break的标簽功能
		
		label:for(int i = 1;i < 3;i++){
			for(int j = 1;j < 5;j++){
				if(j == 4){
//					break;
					break label; //break lable直接結束掉外層循環,終止程式。
//					continue label; //下面【13要點】會提及
				}
				System.out.print(j);
			}
			System.out.println("for lable...");  //break外層循環後,這裡不會被列印了。
		}
		
	}
}
           
13、循環結構&關鍵字continue
continue語句
(1)、continue隻能使用在循環結構中;
(2)、continue語句用于跳過其所在循環語句的一次執行,繼續執行下一次循環;
(3)、continue語句出現在多層嵌套循環的語句體時,可以通過标簽指明要跳過的是哪一層循環 (重點) : 例題可參考【17、代碼4】
           

代碼示範(比較break和continue的差別——重點):

package com.rucoding.d6;

/**
 * @author LiuYiXin
 *
 */
public class BreakContinueDemo01 {
	public static void main(String[] args) {
		//示範break和continue的差別
		for(int i = 1;i <= 10;i++){
			if(i % 4 == 0){
//				break; //輸出123
				continue;//輸出123567910
//				System.out.println();//break、continue後面不能聲明執行語句
			}
			System.out.println(i);
		}
		
		System.out.println("============分割線=============");
		
		for(int i = 1;i <= 4;i++){
			for(int j = 1;j <= 10;j++){
				if(i % 4 == 0){
//					break; //預設跳出包裹此關鍵字最近的一層循環
					continue;
				}
				System.out.print(j);
			}
			System.out.println();
		}
		
		
	}
}
           

小結:

(1)、break隻能用于switch語句和循環語句中。
(2)、continue 隻能用于循環語句中。
(3)、二者功能類似,但continue是終止本次循環,break是終止本層循環。
(4)、break、continue之後不能有其他的語句,因為程式永遠不會執行其後的語句。
(5)、标号語句必須緊接在循環的頭部。标号語句不能用在非循環語句的前面。
           
14、循環結構&關鍵字return
return : 并非專門用于結束循環的,它的功能是結束一個方法的。當一個方法執行到一個return語句的時候,這個方法将被結束。
與break和continue不同的是,return直接結束整個方法,不管這個return處于多少層循環内。
           
15、循環結構&嵌套循環(多重循環)
1、嵌套循環(多重循環)
(1)、将一個循環放在另一個循環體内,就形成了嵌套循環。其中,for、while、do-while均可以作為外層循環或内層循環。
(2)、實質上,嵌套循環就是把内層循環當成外層循環的循環體,當隻有内層循環的循環條件為false時候,才會完全跳出内層循環,才可結束外層的當次循環,開始下一次的循環。
(3)、假設外層循環的次數為m次,内層為n次,則内層循環的實際上執行m*n 次。
           

代碼示範:

package com.rucoding.d6;

/**
 * @author LiuYiXin
 *
 */
public class ForDemo03 {
	/*
	 * 嵌套循環的使用:
	 * 1、嵌套循環:将一個循環結構A聲明再另一個循環結構B結構體中,就形成嵌套循環。
	 * 
	 * 2、外層循環:循環結構B
	 * 	    内層循環:循環結構A
	 * 3、說明:
	 * 	  ①、内層循環周遊一遍,隻相當于外層循環循環體執行一次;
	 * 	  ②、假設外層循環需要執行m次,内層循環需要執行n次,此時内層循環的循環體實際一共執行m*n次
	 * 
	 * 4、技巧
	 * 外層循環控制的是行數,内層循環控制的是列數  (重點記住)
	 */
	public static void main(String[] args) {
		
		//輸出五個星号
		
		for(int i=1;i <=5;i++){
			System.out.print("*");
		}
		
		System.out.println();//換行
		
		//輸出5行 5個星号
		for(int i=1;i <=5;i++){
			for(int j=1;j <=5;j++){
				System.out.print("*");
			}
			System.out.println();
		}
		
		System.out.println("========分割線=======");
		
		/*列印如下圖案1
		*		  	i(外層控制行數) 	j(内層j控制列數)
		**			2   			 2
		***			3				 3
		****		4				 4
		*****		5				 5   即是i=j關系
		*/
		for(int i=1;i <=5;i++){
			for(int j=1;j<=i;j++){
				System.out.print("*");
			}
			System.out.println();
		}
		
	
		
		/* 列印如下圖案2
		*****     i(内層循環控制行數)  j(内層循環控制列數)
		****	  i = 1  j=5 
		***		  i = 2  j=4
		**
		*
		*/
		for(int i=1;i <= 5;i++){
			for(int j=1;j <= (6-i);j++){
				System.out.print("*");
			}
			System.out.println();
		}
		
		
		System.out.println("========分割線=======");
		/*列印如下圖案3
		    * 
		   * * 
		  * * * 
		 * * * * 
		* * * * * 
		 * * * * 
		  * * * 
		   * * 
		    * 
		 */
		//分析:
		/*
		 * 先看上半部分
		 */
		for(int i=1;i <= 5;i++){
			for(int j=0;j <= (5-i);j++){
//				System.out.print("-"); //上半部分左邊的空格, 可以先當做"-"
				System.out.print(" ");
			}
			
			//控制星号
			for(int j=1;j <= i;j++){
				System.out.print("*" + " ");
			}
			
			System.out.println();
		}
		
		
		//下半部分
		for(int i=1;i <= 4;i++){
			for(int j=1;j <= i;j++){
//				System.out.print("-");//下半部分左邊的空格, 可以先當做"-"
				System.out.print(" ");
			}
			
			//控制星号
			for(int j=1;j <= (5-i);j++){
				System.out.print(" " + "*" );
			}
		
			System.out.println();
		}
		
	}
}
           
16、循環結構&嵌套循環練習1

練習1:列印九九乘法表

代碼示範:

package com.rucoding.d6;

/**
 * @author LiuYiXin
 *
 */
public class Print99Demo01 {
	public static void main(String[] args) {
		//列印九九乘法表
		/*
		 * 分析九九乘法表構造
		 * 1 * 1 = 1            i外層控制行數  j内層控制列數
		 * 2 * 1 = 2  2 * 2 = 4
		 * ......
		 * 9 * 1 = 9  9 * 2 = 18 ...... 9 * 9 =81
		 */
		
		for(int i = 1;i <= 9;i++){
			for(int j = 1;j <= i;j++){
				System.out.print(i + " * " + j + " = " + (i*j) + "	");
			}
			System.out.println();
		}
		
	}
}	
           
17、循環結構&嵌套循環練習2

練習2:求100000以内的所有質數個數。

代碼1:

package com.rucoding.d6;

/**
 * @author LiuYiXin
 *
 */
public class PrimeNumberDemo01 {
	//求100000以内的所有質數個數
	public static void main(String[] args) {
		//分析質數(素數)的特點: 隻能被1和它本身整除的自然數。
		//最小的質數:2
		
		/*
		 * 拆解:外層循環控制周遊100000以内的資料,内層循環控制 1 到 它本身 減1 的資料
		 * 
		 */
		boolean isFlag = true;//辨別是否被除盡,一旦除盡,修改其值
		int count = 0;
		
		long startTime = System.currentTimeMillis();//計算程式執行時間
		
		for(int i = 2;i <= 100000;i++){
			for(int j = 2;j < i;j++){// 此時j的作用:能否被i整除
				//
				if(i % j == 0){ //判斷i除以j,隻要有一個能整除 就設定isFlag為false
					isFlag = false;
				}
				
			}
			
			if(isFlag == true){
//				System.out.println(i);
				count++;
			}
			
			isFlag = true; //重置flag
			
		}
		
		long endTime = System.currentTimeMillis();
		System.out.println("100000以内的質數一共有:" + count + " 個");
		System.out.println("計算耗時:" + (endTime - startTime) + " 毫秒");
	}
}
           
【代碼1】運作結果:
100000以内的質數一共有:9592 個
計算耗時:11000 毫秒
           

這運作有點費時,得優化。

代碼2【針對代碼1的優化】:

注意代碼出現的 “優化點1”。

package com.rucoding.d6;

/**
 * @author LiuYiXin
 *
 */
public class PrimeNumberDemo02 {
	//求100000以内的所有質數個數
	public static void main(String[] args) {
		//分析質數(素數)的特點: 隻能被1和它本身整除的自然數。
		//最小的質數:2
		
		/*
		 * 拆解:外層循環控制周遊100000以内的資料,内層循環控制 1 到 它本身 減1 的資料
		 * 
		 */
		boolean isFlag = true;//辨別是否被除盡,一旦除盡,修改其值
		int count = 0;
		
		long startTime = System.currentTimeMillis();//計算程式執行時間
		
		for(int i = 2;i <= 100000;i++){
			for(int j = 2;j < i;j++){// 此時j的作用:能否被i整除
				//優化點1:這裡假如是非質數i為10,
				//那麼此時j的循環是2,3,4..9 (第一個2的時候已經滿足除盡的,後面就沒必要再執行了)
				if(i % j == 0){ //判斷i除以j,隻要有一個能整除 就設定isFlag為false
					isFlag = false;
					break;//第一個進來滿足除盡了,後面的數字沒必要再進行一遍整除了。
				}
				
			}
			
			if(isFlag == true){
//				System.out.println(i);
				count++;
			}
			
			isFlag = true; //重置flag
			
		}
		
		long endTime = System.currentTimeMillis();
		System.out.println("100000以内的質數一共有:" + count + " 個");
		System.out.println("計算耗時:" + (endTime - startTime) + " 毫秒");
	}
}
           
【代碼2】運作結果:
100000以内的質數一共有:9592 個
計算耗時:1078 毫秒
           

繼續觀察,發現是還可以進行優化的。

代碼3【針對代碼2的優化】:

注意代碼出現的 “優化點2”。

package com.rucoding.d6;

/**
 * @author LiuYiXin
 *
 */
public class PrimeNumberDemo03 {
	//求100000以内的所有質數個數
	public static void main(String[] args) {
		//分析質數(素數)的特點: 隻能被1和它本身整除的自然數。
		//最小的質數:2
		
		/*
		 * 拆解:外層循環控制周遊100000以内的資料,内層循環控制 1 到 它本身 減1 的資料
		 * 
		 */
		boolean isFlag = true;//辨別是否被除盡,一旦除盡,修改其值
		int count = 0;
		
		long startTime = System.currentTimeMillis();//計算程式執行時間
		
		for(int i = 2;i <= 100000;i++){
			for(int j = 2;j <= Math.sqrt(i);j++){// 此時j的作用:能否被i整除  
				//優化點2:這裡的循環條件部分(j < i) ,範圍可以縮減,剛開始考慮的i/2,縮減了一半,後面再觀察考慮一下,開根号可以大大縮減,實在秒啊!
				//優化點1:這裡假如是非質數i為10,
				//那麼此時j的循環是2,3,4..9 (第一個2的時候已經滿足除盡的,後面就沒必要再執行了)
				if(i % j == 0){ //判斷i除以j,隻要有一個能整除 就設定isFlag為false
					isFlag = false;
					break;//優化點1:第一個進來滿足除盡了,後面的數字沒必要再進行一遍整除了。
				}
				
			}
			
			if(isFlag == true){
//				System.out.println(i);
				count++;
			}
			
			isFlag = true; //重置flag
			
		}
		
		long endTime = System.currentTimeMillis();
		System.out.println("100000以内的質數一共有:" + count + " 個");
		System.out.println("計算耗時:" + (endTime - startTime) + " 毫秒");
	}
}
           
【代碼3】運作結果:
100000以内的質數一共有:9592 個
計算耗時:15 毫秒
           

繼續優化,代碼看着不太友好。

代碼4【針對以上代碼的優化】:

Tip:此處利用了continue标簽。

package com.rucoding.d6;

/**
 * @author LiuYiXin
 *
 */
public class PrimeNumberDemo04 {
	//求100000以内的所有質數個數
	public static void main(String[] args) {
		//分析質數(素數)的特點: 隻能被1和它本身整除的自然數。
		//最小的質數:2
		
		/*
		 * 拆解:外層循環控制周遊100000以内的資料,内層循環控制 1 到 它本身 減1 的資料
		 * 
		 */
	
		int count = 0;
		
		long startTime = System.currentTimeMillis();//計算程式執行時間
		
		label:for(int i = 2;i <= 100000;i++){
			for(int j = 2;j <= Math.sqrt(i);j++){// 此時j的作用:能否被i整除  
				//
				if(i % j == 0){ //判斷i除以j,能否除盡
					continue label;//可以除盡的話,直接後面不用繼續了,跳出目前的循環,繼續下一次循環
				}
			}
			//能走到這裡, 證明已經是質數了。
			count++;
		}
		
		long endTime = System.currentTimeMillis();
		System.out.println("100000以内的質數一共有:" + count + " 個");
		System.out.println("計算耗時:" + (endTime - startTime) + " 毫秒");
	}
}
           
【代碼4】運作結果:
100000以内的質數一共有:9592 個
計算耗時:13 毫秒