第九章 循環結構進階段


一、本章目標

  • 掌握二重循環的使用

  • 掌握二重循環中跳轉語句的使用

二、知識點

1 二重循環

1.1 回顧循環

問題:某次程序大賽,S1班有4名學員參加,學員的成績由用戶輸入,計算該班參賽學員的平均分 

            

實現:

 
 
 
         
  1. /**

  2. * 計算一個班的平均分

  3. */

  4. public class AvgScore {

  5. public static void main(String args[]){

  6. int[] score = new int[4]; //成績數組

  7. float sum = 0.0f; //成績總和

  8. float average = 0.0f; //成績平均值

  9. //循環輸入學員成績

  10. Scanner input = new Scanner(System.in);

  11. System.out.println("請輸入4位學員的成績");

  12. for(int i = 0; i < score.length; i++){

  13. System.out.print("第"+ (i+1) +"位學員的成績:");

  14. score[i] = input.nextInt();

  15. sum = sum + score[i];     //成績累加

  16. }

  17. average = sum / score.length; //計算平均值

  18. System.out.println("參賽學員的平均分是:" + average);

  19. }

  20. }

1.2 為什么使用二重循環

問題:若有3個班級各4名學員參賽,如何計算每個班級參賽學員的平均分?

            

分析:

    使用二循環

    外層循環控制班級數目,內層循環控制每個班級學員數目

1.3 什么是二循環

    一個循環體內又包含另一個完整的循環結構 

    

特點:外層循環變量變化一次,內層循環變量要變化一遍

1.4 使用二重循環

解決上面的問題

  
  
  
          
  1. /**
  2. * 計算3個班級的平均分
  3. */
  4. public class AvgScore {
  5. public static void main(String args[]){
  6. int[] score = new int[4]; //成績數組
  7. int classNum = 3; //班級數目
  8. double sum = 0.0; //成績總和
  9. double average = 0.0; //平均成績
  10. //循環輸入學員成績
  11. Scanner input = new Scanner(System.in);
  12. for(int i = 0; i < classNum; i++){
  13. sum = 0.0f; //成績總和歸0
  14. System.out.println("請輸入第" + (i+1) + "個班級的成績");
  15. for(int j = 0; j < score.length; j++){
  16. System.out.print("第" + (j+1) + "個學員的成績:");
  17. score[j] = input.nextInt();
  18. sum = sum + score[j]; //成績累加
  19. }
  20. average = sum / score.length; //計算平均分
  21. System.out.println("第" + (i+1) + "個班級參賽學員的平均分是:" + average + "\n");
  22. }
  23. }
  24. }
問題二:打印矩形圖案

分析:

  • 用二重循環實現

    • 外層循環控制行數

    • 內層循環控制每行的*號數

實現

  
  
  
          
  1. /**
  2. * 打印矩形
  3. */
  4. public class Rectangle {
  5. public static void main(String[] args) {
  6. System.out.println("打印矩形");
  7. for(int i = 0; i < 5; i++){
  8. for(int j = 0; j <5; j++){
  9. System.out.print("*");
  10. }
  11. System.out.print("\n"); //換行
  12. }
  13. }
  14. }

1.5 技能訓練

訓練1:打印直角三角形

問題:打印直角三角形 

  • 從控制台輸入直角三角形的高度(行數)

  • 每行 * 的數目依次為1、3、5、7…

分析:

    1.外層循環控制行數 

    2.分析每行打印的內容

    3.每一行打印字符*結束后要換行

    4.內層循環的條件: j<=2i-1

實現

  
  
  
          
  1. /**
  2. * 輸入行數打印直角三角形
  3. */
  4. public class RTriAngle {
  5. public static void main(String[] args) {
  6. int rows = 0; //三角形行數
  7. System.out.print("請輸入直角三角形的行數:");
  8. Scanner input = new Scanner(System.in);
  9. rows = input.nextInt();
  10. //打印直角三角形
  11. for(int i = 1; i <= rows; i++){
  12. for(int j = 1; j <= 2*i-1; j++){
  13. System.out.print("*");
  14. }
  15. System.out.print("\n");
  16. }
  17. }
  18. }

訓練二:打印倒直角三角形

需求說明:

  • 從控制台輸入直角三角形的高度(行數)

  • 每行*的數目從下至上依次為1、2、3、4…

實現

  
  
  
          
  1. /**
  2. * 輸入行數打印倒直角三角形
  3. */
  4. public class InvertRTriAngle {
  5. public static void main(String[] args) {
  6. int rows = 0; //三角形行數
  7. System.out.print("請輸入直角三角形的行數:");
  8. Scanner input = new Scanner(System.in);
  9. rows = input.nextInt();
  10. //打印倒直角三角形
  11. for(int i = 1; i <= rows; i++){
  12. for(int j = 1; j <= rows+1-i; j++){
  13. System.out.print("*");
  14. }
  15. System.out.print("\n");
  16. }
  17. }
  18. }

訓練三:打印等腰三角形

需求說明

  • 從控制台輸入等腰三角形的高度

  • 每行*的數目依次為1、3、5、7… 

        

分析:

  • 外層循環控制行數

  • 每行先打印空格,再打印*

  • 打印空格和字符*用兩個不同的循環

實現

  
  
  
          
  1. /**
  2. * 輸入行數打印等腰三角形
  3. */
  4. public class IsoTriangle {
  5. public static void main(String[] args) {
  6. int rows = 0; //三角形行數
  7. System.out.print("請輸入等腰三角形的行數:");
  8. Scanner input = new Scanner(System.in);
  9. rows = input.nextInt();
  10. //打印等腰三角形
  11. for(int i = 1; i <= rows; i++){
  12. for(int j = 1; j <= rows-i; j++){
  13. System.out.print(" ");
  14. }
  15. for(int k = 1; k <= 2*i-1; k++){
  16. System.out.print("*");
  17. }
  18. System.out.print("\n");
  19. }
  20. }
  21. }

訓練四:打印九九乘法表

需求說明

  • 利用二重循環實現九九乘法表

分析:

    1.九九乘法表共有9行,因此外層循環條件為

                i<=9

    2.第i行上有i個式子,因此因此外層循環條件為

             j <=i

    3.第i行上的第j個式子為

                 j的值 * i的值 = j*i的值

實現

  
  
  
          
  1. /**
  2. * 打印九九乘法表
  3. */
  4. public class MulTable {
  5. public static void main(String[] args) {
  6. int rows = 9; //乘法表的行數
  7. for(int i = 1; i<=rows; i++){ //一共9行
  8. for(int j = 1; j <= i; j++){ //第i行有i個式子
  9. System.out.print(j+"*"+i+"="+j*i+" ");
  10. }
  11. System.out.print("\n"); //打印完一行后換行
  12. }
  13. }
  14. }

2 跳轉語句進階

2.1 在二重循環中使用continue 

問題:

    若有3個班級各4名學員參賽,計算每個班級參賽學員平均分,統計成績大於85分學員數 

分析

  • 在問題1基礎上增加了新功能

  • 使用continue統計大於85分的學員人數

實現

  
  
  
          
  1. /**
  2. * continue斷點演示:計算成績85分以上的學員人數
  3. *
  4. */
  5. public class ContinueDemo {
  6. public static void main(String[] args) {
  7. int[] score = new int[4]; //成績數組
  8. int classnum = 3; //班級數目
  9. double sum = 0.0; //成績總和
  10. double average = 0.0; //平均成績
  11. int count = 0; //記錄85分以上學員人數
  12. //循環輸入學員成績
  13. Scanner input = new Scanner(System.in);
  14. for(int i = 0; i < classnum; i++){
  15. sum = 0.0f; //成績總和歸0
  16. System.out.println("請輸入第" + (i+1) + "個班級的成績");
  17. for(int j = 0; j < score.length; j++){
  18. System.out.print("第" + (j+1) + "個學員的成績:");
  19. score[j] = input.nextInt();
  20. sum = sum + score[j]; //成績累加
  21. if(score[j] < 85){ //成績小於85,則跳出本輪循環
  22. continue;
  23. }
  24. count++;
  25. }
  26. average = sum / score.length;
  27. System.out.println("第" + (i+1) + "個班級參賽學員的平均分是:" + average + "\n");
  28. }
  29. System.out.println("成績85分以上的學員人數有" + count + "人");
  30. }
  31. }

2.2 在二重循環中使用break 

問題:

  • 有5家衣服專賣店,每家最多購買3件。用戶可以選擇離開,可以買衣服

  • 最后打印總共買了幾件衣服 

分析:

  • 使用二重循環解決

    • 外層循環控制去每個專賣店

    • 內層循環控制買衣服過程

    • 使用break退出內層循環

實現

  
  
  
          
  1. /**
  2. * break斷點演示:實現購物結賬
  3. */
  4. public class BreakDemo {
  5. public static void main(String[] args) {
  6. int count = 0;    //記錄一共買了幾件衣服
  7. String choice;    //顧客選擇是否離開
  8. Scanner input = new Scanner(System.in);
  9. for(int i = 0; i < 5; i++){
  10. System.out.println("歡迎光臨第" + (i+1) + "家專賣店");
  11. for(int j = 0; j < 3; j++){
  12. System.out.print("要離開嗎(y/n)?");
  13. choice = input.nextLine();
  14. if("y".equals(choice)){    //如果離開,則跳出,進入下一家店
  15. break;
  16. }
  17. System.out.println("買了一件衣服");
  18. count++;
  19. }
  20. System.out.println("離店結賬\n");
  21. }
  22. System.out.println("總共買了" + count + "件衣服");
  23. choice = input.nextLine();
  24. }
  25. }

2.3 二重循環中continue和break對比 

  • continue:繼續本層下一輪循環

  • break:跳出本層循環

2.4 技能訓練

訓練一:統計打折商品數量

需求說明:

  • 有3名顧客去商場購物,每人買3件商品

  • 商品單價300元以上的商品享受8折優惠

  • 請統計每人享受打折優惠的商品的數量

分析:

  • 外層循環條件:i<3

  • 內層循環條件:j<3

  • 使用continue統計享受優惠的商品數量

實現

  
  
  
          
  1. /**
  2. * 統計打折商品數量
  3. */
  4. public class Demo {
  5. public static void main(String[] args) {
  6. int count = 0;    //記錄打折商品數量
  7. Scanner input = new Scanner(System.in);
  8. double price=0.0; //商品價格
  9. for(int i = 0; i < 3; i++){
  10. System.out.println("請輸入第"+(i+1) +"個人所購的三件商品的價格:");
  11. for(int j = 0; j < 3; j++){
  12. price=input.nextDouble();
  13. if(price<300)
  14. continue;
  15. count++ ; //累計
  16. }
  17. System.out.println("第"+(i+1) +"個人共有" +count + "件商品享受8折優惠!");
  18. count=0;//重置count值
  19. }
  20. }
  21. }

3 作業

1 打印數字組成的直角三角形


實現

  
  
  
          
  1. public class NumberTriangle {
  2. /**
  3. * 打印數字組成的直角三角形
  4. */
  5. public static void main(String[] args) {
  6. int rows = 5;
  7. for(int i = 1; i <= rows; i++){
  8. for(int j = 1; j <= i; j++){
  9. System.out.print(j);
  10. }
  11. System.out.print("\n");
  12. }
  13. }
  14. }

2 百錢買百雞,5文錢可以買一只公雞,3文錢可以買一只母雞,1文錢可以買3只雛雞。現在用100文錢買100只雞,那么公雞、母雞、雛雞各多少只?


實現

  
  
  
          
  1. public class Chook {
  2. /**
  3. * 百錢買百雞
  4. */
  5. public static void main(String[] args) {
  6. int way = 1; //買法
  7. int k = 0; //雛雞數
  8. for(int i=1;i<=20;i++){ //公雞數
  9. for(int j=1;j<=33;j++){ //母雞數
  10. k = 100-i-j; //一共100只雞
  11. if(k%3 == 0 && (5*i+3*j+k/3 == 100)){//雛雞數是3的倍數,總計100文錢
  12. System.out.print("[買法 " + way++ + "] ");
  13. System.out.println("公雞: " +i+ " 母雞:" +j+ " 雛雞:" +k);
  14. }
  15. }
  16. }
  17. }
  18. }

3 有3個班級各4名學員參賽,從控制台輸入每個班級參賽學員的成績,要求統計3個班級所有參賽學員成績大於85分的學員的平均分,如何編程

實現

  
  
  
          
  1. /**
  2. * continue斷點演示:計算成績85分以上的學員人數
  3. *
  4. */
  5. public class AvgScore {
  6. public static void main(String[] args) {
  7. int[] score = new int[4]; //成績數組
  8. int classnum = 3; //班級數目
  9. double sum = 0.0; //成績總和
  10. double average = 0.0; //平均成績
  11. int count = 0; //記錄85分以上學員人數
  12. //循環輸入學員成績
  13. Scanner input = new Scanner(System.in);
  14. for(int i = 0; i < classnum; i++){
  15. System.out.println("請輸入第" + (i+1) + "個班級的成績");
  16. for(int j = 0; j < score.length; j++){
  17. System.out.print("第" + (j+1) + "個學員的成績:");
  18. score[j] = input.nextInt();
  19. if(score[j] < 85){ //成績小於85,則跳出本輪循環
  20. continue;
  21. }
  22. sum = sum + score[j]; //成績85分以上才進行累加
  23. count++;
  24. }
  25. }
  26. average = sum / count; //所有成績85分以上的學員的平均分
  27. System.out.println("所有成績85分以上的學員的平均分為:" + average);
  28. }
  29. }

4 假設一個簡單的ATM的取款過程如下:首先提示用戶輸入密碼,最多只能輸入3次,超過3次則提示用戶“密碼錯誤,請取卡”,結束交易。如果用戶密碼正確,再提示用戶輸入金額,ATM只能輸出100元的紙幣,一次取錢數要求最低0元,最高1000元。如果用戶輸入的金額符合上述要求,則打印輸出用戶取的錢數,最后提示用戶“交易完成,請取卡”,否則提示用戶重新輸入金額。假設用戶密碼是111111.

實現:

  
  
  
          
  1. public class ATMDemo {
  2. /**
  3. * 簡單ATM機取款過程模擬
  4. */
  5. public static void main(String[] args) {
  6. String pass = ""; //保存用戶輸入密碼
  7. int amount = 0; //取款金額
  8. String password = "111111"; //用戶密碼
  9. int count = 0; //記錄密碼輸入次數
  10. boolean isPass = false; //密碼是否通過驗證
  11. Scanner input = new Scanner(System.in);
  12. while(count < 3 && !isPass){
  13. System.out.print("請輸入密碼:");
  14. pass = input.next();
  15. if(!password.equals(pass)){
  16. count++;
  17. continue;
  18. }
  19. isPass = true; //密碼通過驗證
  20. System.out.print("請輸入金額:");
  21. amount = input.nextInt();
  22. while(amount>0){
  23. if(amount<=1000 && amount%100==0){
  24. System.out.println("您取了" +amount+ "元");
  25. System.out.println("交易完成,請取卡!");
  26. break; //完成交易,退出
  27. }else{
  28. System.out.print("您輸入金額的金額不合法,請重新輸入:");
  29. amount = input.nextInt();
  30. continue; //繼續讓用戶輸入金額
  31. }
  32. }
  33. }
  34. if(!isPass){ //用戶輸入了3次錯誤密碼
  35. System.out.print("密碼錯誤,請取卡!");
  36. }
  37. }
  38. }

5 輸入行數,打印菱形,要求如下:

  • 從控制台輸入菱形的高度(行數)。如果用戶輸入的行數合法(奇數),則打印出菱形,否則提示用戶輸入奇數

  • 假設用戶輸的行數為rows,則每行字符*的個數依次為1,3,5,7...,rows,...7,5,3,1

實現

  
  
  
          
  1. /**
  2. * 輸入行數打印菱形
  3. */
  4. public class Diamond {
  5. public static void main(String[] args) {
  6. int rows = 0; //菱形的行數
  7. Scanner input = new Scanner(System.in);
  8. System.out.print("請輸入菱形行數:");
  9. rows = input.nextInt();
  10. while(rows%2 == 0){
  11. System.out.print("請輸入奇數:");
  12. rows = input.nextInt();
  13. }
  14. int n = (rows+1)/2;
  15. //打印菱形的上半部分
  16. for(int i = 1; i <= n; i++){//外層循環變量i控制行數
  17. for(int j = 1; j <= n-i; j++){//內層循環變量j控制該行空格數
  18. System.out.print(" ");
  19. }
  20. for(int k = 1; k <= 2*i-1; k++){//內層循環變量k控制該行*號數
  21. System.out.print("*");
  22. }
  23. System.out.print("\n");
  24. }
  25. //打印菱形的下半部分
  26. for(int i = n-1; i >= 1; i--){
  27. for(int j = 1; j <= n-i; j++){
  28. System.out.print(" ");
  29. }
  30. for(int k = 1; k <= 2*i-1; k++){
  31. System.out.print("*");
  32. }
  33. System.out.print("\n");
  34. }
  35. }
  36. }

總結

  • 二重循環是一個循環體內又包含另一個完整的循環結構

  • 在二重循環中,外層循環變量變化一次,內層循環變量要從初始值到結束值變化一遍

  • 在二重循環中可以使用break、continue語句控制程序的執行

    關注我們


    捐贈我們

        良師益友工作室一直在致力於幫助編程愛好更加快速方便地學習編程,如果您對我們的成果表示認同並且覺得對你有所幫助,歡迎您對我們捐贈^_^。
        




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM