Java 巢狀迴圈及示例


Java 中的迴圈被稱為控制語句,因為它們根據某些條件決定程式的執行流程。 Java 允許巢狀迴圈,當我們將一個迴圈放在另一個迴圈內時,我們稱之為巢狀迴圈。巢狀迴圈在我們需要遍歷矩陣陣列以及我們需要進行任何基於模式的問題時非常有用。

在本文中,我們將學習 Java 巢狀迴圈及示例。

我們可以為以下控制語句建立巢狀迴圈:

讓我們透過一些示例來討論這些巢狀迴圈。

巢狀 for 迴圈

在任何程式語言中,for 迴圈是最常用的控制語句,因為它易於理解和實現。迴圈迭代直到給定條件為真。巢狀 for 迴圈是指另一個 for 迴圈中的 for 迴圈。

語法

for (initial expression; conditional expression; increment/decrement expression){
   // code to be executed
   for (initial expression; conditional expression; increment/decrement expression) {
      // code to be executed
   }
}

初始表示式 - 迴圈開始時執行一次。

條件表示式 - 程式碼將執行直到條件表示式為真。

增量/減量表達式 - 用於增量/減量迴圈變數。

示例

以下程式將使用巢狀 for 迴圈執行兩個矩陣的加法。

public class Main{
   public static void main(String args[]){
      int mtr1[][] = {{2,7},
      {9,2}};
      int mtr2[][] = {{6,3},
      {5,1}};
      int add[][] = new int[2][2];
      // Nested for loop
      for (int i= 0 ; i < 2 ; i++ ){ 
         for (int j= 0 ; j < 2 ;j++ ){
            add[i][j] = mtr1[i][j] + mtr2[i][j]; 
            // Performing addition
         }
      }
      System.out.println("Sum of given two matrices =");
      // Nested for loop to print the resulted matrix
      for (int i= 0 ; i < 2 ; i++ ){
         for (int j= 0 ; j < 2 ;j++ ){
            System.out.print(add[i][j]+"\t");
         }
         System.out.println();
      }
   }
}

輸出

Sum of given two matrices =
8   10
14   3

在上面的程式碼中,我們取了兩個大小為 2 行 2 列的矩陣 mtr1mtr2。前兩個 for 迴圈將執行 4 次,並且在每次迭代期間,mtr1mtr2 的值將儲存在第三個矩陣 add 中。最後兩個 for 迴圈將在螢幕上列印結果。


巢狀 while 迴圈

while 迴圈中,條件在進入迴圈體之前進行檢查,因此它是一個入口控制迴圈。巢狀 while 迴圈是指另一個 while 迴圈內的 while 迴圈。


語法

while (conditional expression) {
   // code will be executed till the conditional expression is true
   while (conditional expression) {
      // code will be executed till the conditional expression is true
      increment/decrement expression; 
      // to increment/decrement loop variable
   }
   increment/decrement expression; 
   // to increment/decrement loop variable
}

示例

以下程式將使用 while 迴圈執行兩個矩陣的加法。

public class Main{
   public static void main(String args[]){
      int mtr1[][] = {{2,7},{9,2}};
      int mtr2[][] = {{6,3},{5,1}};
      int add[][] = new int[2][2];
      int i=0;
      // Nested while loop to perform addition
      while(i<2){
         int j=0;
         while(j<2){
            add[i][j] = mtr1[i][j] + mtr2[i][j]; 
            j++;
         }
         i++;
      }
      System.out.println("Sum of given two matrices =");
      i=0;
      // Nested while loop to print result
      while(i<2){
         int j=0;
         while(j<2){
            System.out.print(add[i][j]+"\t");
            j++;
         }
         System.out.println();
         i++;
      }
   }
}

輸出

Sum of given two matrices =
8    10
14    3

在上面的程式碼中,我們遵循了與示例 1 程式中相同的邏輯,但這裡我們使用了巢狀 while 迴圈而不是 for 迴圈。同樣,我們取了兩個大小為 2 行 2 列的矩陣 mtr1mtr2。前兩個 while 迴圈將執行 4 次,並且在每次迭代期間,mtr1mtr2 的值將儲存在第三個矩陣 add 中。最後兩個 while 迴圈將在螢幕上列印結果。

巢狀 do while 迴圈

do while 迴圈中,在檢查給定的測試條件之前,迴圈體先執行,因此它是一個出口控制迴圈。巢狀 do while 迴圈也可以透過在一個do-while 迴圈中使用另一個do-while 迴圈來建立。

語法

do{
    //statement for the outer loop
    do{
      //statement for the inner loop inner
    }while(condition B);
}while(condition A)

示例

此 Java 程式使用巢狀的do-while 迴圈來列印星號(*)網格。

public class Main {
    public static void main(String[] args) {
	    int rows = 3;
	    int cols = 4;
	    int i = 1;
	    do {
                    int j = 1;
	        do {
	              System.out.print("* ");
		      j++;
		}
		while (j <= cols);
		System.out.println();
	        i++;
	    }
        while (i <= rows);
    }
}

輸出

* * * * 
* * * * 
* * * * 

在上面的程式碼中,外迴圈執行三次,每次執行一行,並在每次行迭代時初始化一個內迴圈。內迴圈執行四次,每次執行一列,並列印一個星號後跟一個空格。在列印完一行所需的星號後,內迴圈結束,程式移到下一行。此過程重複,直到列印完所有行。外迴圈確保內迴圈為指定行數執行,從而生成一個3x4 星號網格

巢狀 for each 迴圈

一個for each 迴圈是一種特殊的重複控制結構,它允許你有效地編寫一個需要執行特定次數的迴圈。巢狀 for each 迴圈是指在一個 for each 迴圈中使用另一個 for each 迴圈。

語法

for (Type[] arrayElement : outerArray) {
    for (Type element : arrayElement) {
        // Inner loop statements
    }
}

示例

此 Java 程式演示瞭如何使用巢狀 for-each 迴圈遍歷字串的二維陣列並列印其元素。

public class NestedForEachExample3 {
    public static void main(String[] args) {
        String[][] array = {
            {"apple", "banana", "cherry"},
            {"dog", "elephant", "frog"},
            {"grape", "honey", "ice"}
        };

        for (String[] row : array) {
            for (String element : row) {
                System.out.print(element + " ");
            }
            System.out.println();
        }
    }
}

陣列變數是一個二維陣列,包含三行,每行包含三個字串。外層 for-each 迴圈遍歷陣列的每一行。對於每一行,內層 for-each 迴圈遍歷該行的元素。每個字串元素後跟一個空格列印。處理完一行中的所有元素後,二維陣列的每一行結果都列印在新的一行上。

結論

一個迴圈在另一個迴圈內被稱為巢狀迴圈。我們已經理解了巢狀 for 迴圈和巢狀 while 迴圈以及示例。當我們需要對二維陣列和矩陣執行操作時,我們會使用這些迴圈。我們還在基於模式的問題中使用它們。

更新於: 2024-07-31

1K+ 閱讀量

開啟你的職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.