迴圈是讓程式中可以有某部分程式能夠被重複執行多次,每一次重複執行,稱之為一個iteration。
而在Java, 有三種迴圈分別是for、while和do。
for 迴圈 (for loop)
for 迴圈語法
一開始進入for loop會先執行初值運算式,然後檢查條件運算式是否成立(結果是否為true),決定是否執行迴圈內的敘述區塊。
for(初值運算式;條件運算式;增量運算式)
{ …… 敘述區塊 …… }
用for loop做九九乘法表
public class MultiplicationTable {
    public static void main(String[] args) {
        for(int j = 1; j < 10; j++) { 
           for(int i = 2; i < 10; i++) { 
               System.out.printf("%d*%d=%2d ",i, j,  i * j);
           } 
           System.out.println(); 
        }  
    }
}
while 迴圈(while loop)
while 迴圈語法
執行迴圈前先檢查條件運算式來判斷是否執行迴圈內的敘述區塊。
while(條件運算式) {
    …… 敘述區塊 ……
} 
用while loop數 0 到 10
public class WhileLoopExample {
    public static void main(String[] args) {
        int counter = 1; // Initialize a counter variable to 1
        // Use a while loop to print numbers from 1 to 5
        while (counter <= 10) {
            System.out.println("Number: " + counter);
            counter++; // Increment the counter
        }
    }
}
do-while迴圈(do while loop)
do-while迴圈語法
先執行敘述區塊一次後,再判斷是否要繼續重覆執行迴圈。
do { 
    …… 敘述區塊 ……
 } while(條件運算式);
用do-while 來做正數檢查
import java.util.Scanner;
public class DoWhileLoopExample {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int number;
        boolean isValidInput;
        do {
            System.out.print("Enter a positive number: ");
            if (scanner.hasNextInt()) {
                number = scanner.nextInt();
                if (number > 0) {
                    isValidInput = true;
                } else {
                    isValidInput = false;
                    System.out.println("Please enter a positive number.");
                }
            } else {
                isValidInput = false;
                System.out.println("Invalid input. Please enter a valid number.");
                scanner.next(); // Consume the invalid input
            }
        } while (!isValidInput);
        System.out.println("You entered a valid positive number: " + number);
        // Close the scanner
        scanner.close();
    }
}