Control Flow: if, switch, for, while, do-while

บทนำ: การควบคุมการไหลของโปรแกรม

จนถึงตอนนี้ โปรแกรมที่เราเขียนทำงานแบบ เชิงเส้น (Sequential) – คำสั่งทำงานตามลำดับ จากบนลงล่าง โดยไม่มีการตัดสินใจ

Control Flow (การควบคุมการไหล) คือ การทำให้โปรแกรม “คิด” โดยการ:

  1. ตัดสินใจ (Decision) – ถ้าเงื่อนไขนี้ให้ทำสิ่งนี้ ถ้าไม่ให้ทำอย่างอื่น
  2. ทำซ้ำ (Loop) – ทำคำสั่งซ้ำๆ หลายครั้ง
ยาวไป อยากเลือกอ่าน
  1. บทนำ: การควบคุมการไหลของโปรแกรม
  2. Decision-Making: ตัดสินใจ
  3. 1. if Statement: ถ้าเงื่อนไข
  4. โครงสร้าง if
  5. if-else: ถ้าไม่เป็นจริง
  6. if-else if-else: เงื่อนไขหลายขั้น
  7. Nested if: if ซ้อน if
  8. 2. switch Statement: เลือกหลายทางเลือก
  9. Loops: การทำซ้ำ
  10. เหตุผลของ Loop
  11. 1. for Loop: ทำซ้ำตามจำนวนครั้ง
  12. โครงสร้าง for
  13. ตัวอย่าง: คำนวณผลรวม
  14. ตัวอย่าง: ตารางสูตรคูณ
  15. for loop ลดลง
  16. 2. while Loop: ทำซ้ำตามเงื่อนไข
  17. โครงสร้าง while
  18. ตัวอย่าง: รับข้อมูลจนกว่า user พอ
  19. ตัวอย่าง: ตรวจสอบ Password
  20. 3. do-while Loop: ทำก่อน แล้วค่อยตรวจสอบ
  21. โครงสร้าง do-while
  22. ความแตกต่าง while vs do-while
  23. ตัวอย่าง: ระบบเมนูแบบวนซ้ำ
  24. Loop Control: ควบคุมการ Loop
  25. break: ออกจาก Loop
  26. continue: ข้ามไปรอบต่อไป
  27. ตัวอย่าง: หาเลขคี่
  28. Nested Loops: Loop ซ้อน Loop
  29. ตัวอย่าง: สี่เหลี่ยมตัวอักษร
  30. ตัวอย่าง: ตาราง
  31. ตัวอย่าง: สามเหลี่ยม
  32. สรุป: Control Flow
  33. ตัวอย่างการใช้ทั้งหมดรวมกัน

Decision-Making: ตัดสินใจ

1. if Statement: ถ้าเงื่อนไข

if ใช้สำหรับ ตรวจสอบเงื่อนไข และ ทำสิ่งใดสิ่งหนึ่งตามผลลัพธ์

โครงสร้าง if

javaif (condition) {
    // ทำสิ่งนี้ถ้า condition เป็น true
}

ตัวอย่าง:

javapublic class IfDemo {
    public static void main(String[] args) {
        int age = 20;
        
        if (age >= 18) {
            System.out.println("You are an adult");
        }
    }
}

Output:

textYou are an adult

if-else: ถ้าไม่เป็นจริง

เมื่อ condition เป็น false ให้ทำคำสั่งใน else block

javaif (condition) {
    // ทำสิ่งนี้ถ้า condition เป็น true
} else {
    // ทำสิ่งนี้ถ้า condition เป็น false
}

ตัวอย่าง:

javapublic class IfElseDemo {
    public static void main(String[] args) {
        int age = 15;
        
        if (age >= 18) {
            System.out.println("You are an adult");
        } else {
            System.out.println("You are a minor");
        }
    }
}

Output:

textYou are a minor

if-else if-else: เงื่อนไขหลายขั้น

เมื่อมีเงื่อนไขมากกว่า 2 ตัว ใช้ else if

javaif (condition1) {
    // ทำสิ่งนี้ถ้า condition1 เป็น true
} else if (condition2) {
    // ทำสิ่งนี้ถ้า condition1 เป็น false และ condition2 เป็น true
} else if (condition3) {
    // ทำสิ่งนี้ถ้า condition1 และ condition2 เป็น false แต่ condition3 เป็น true
} else {
    // ทำสิ่งนี้ถ้าทั้งหมดเป็น false
}

ตัวอย่าง: ระบบให้คะแนนเกรด

javapublic class GradeSystem {
    public static void main(String[] args) {
        int score = 78;
        String grade;
        
        if (score >= 80) {
            grade = "A";
        } else if (score >= 70) {
            grade = "B";
        } else if (score >= 60) {
            grade = "C";
        } else if (score >= 50) {
            grade = "D";
        } else {
            grade = "F";
        }
        
        System.out.println("Score: " + score);
        System.out.println("Grade: " + grade);
    }
}

Output:

textScore: 78
Grade: B

ตัวอย่าง: ระบบตรวจสอบน้ำหนักเหมาะสม

javapublic class BMIChecker {
    public static void main(String[] args) {
        double height = 1.75;  // เมตร
        double weight = 68;    // กิโลกรัม
        double bmi = weight / (height * height);
        
        System.out.printf("Your BMI: %.2f\n", bmi);
        
        if (bmi < 18.5) {
            System.out.println("Category: Underweight");
        } else if (bmi < 25) {
            System.out.println("Category: Normal weight");
        } else if (bmi < 30) {
            System.out.println("Category: Overweight");
        } else {
            System.out.println("Category: Obese");
        }
    }
}

Output:

textYour BMI: 22.20
Category: Normal weight

Nested if: if ซ้อน if

javaif (condition1) {
    if (condition2) {
        // ทำสิ่งนี้ถ้า condition1 AND condition2 เป็น true
    }
}

ตัวอย่าง:

javapublic class NestedIfDemo {
    public static void main(String[] args) {
        int age = 25;
        double salary = 35000;
        
        // ตรวจสอบอายุก่อน
        if (age >= 18) {
            System.out.println("Age requirement: OK");
            
            // แล้วตรวจสอบเงินเดือน
            if (salary >= 30000) {
                System.out.println("Salary requirement: OK");
                System.out.println("Approved for loan!");
            } else {
                System.out.println("Salary requirement: NOT OK");
                System.out.println("Denied - insufficient salary");
            }
        } else {
            System.out.println("Age requirement: NOT OK");
            System.out.println("Denied - too young");
        }
    }
}

Output:

textAge requirement: OK
Salary requirement: OK
Approved for loan!

2. switch Statement: เลือกหลายทางเลือก

switch ใช้เมื่อมีตัวแปร 1 ตัวและต้องเปรียบเทียบกับค่าหลายๆ ค่า

javaswitch (expression) {
    case value1:
        // ทำสิ่งนี้ถ้า expression == value1
        break;
    case value2:
        // ทำสิ่งนี้ถ้า expression == value2
        break;
    default:
        // ทำสิ่งนี้ถ้าไม่ตรงกับ case ใดๆ
}

ตัวอย่าง: ระบบเลือกเมนู

javapublic class SwitchDemo {
    public static void main(String[] args) {
        int day = 3;
        String dayName;
        
        switch (day) {
            case 1:
                dayName = "Monday";
                break;
            case 2:
                dayName = "Tuesday";
                break;
            case 3:
                dayName = "Wednesday";
                break;
            case 4:
                dayName = "Thursday";
                break;
            case 5:
                dayName = "Friday";
                break;
            case 6:
                dayName = "Saturday";
                break;
            case 7:
                dayName = "Sunday";
                break;
            default:
                dayName = "Invalid day";
        }
        
        System.out.println("Day " + day + " is " + dayName);
    }
}

Output:

textDay 3 is Wednesday

ตัวอย่าง: ระบบเลือกการชำระเงิน

javapublic class PaymentSystem {
    public static void main(String[] args) {
        int paymentMethod = 2;
        String method;
        
        switch (paymentMethod) {
            case 1:
                method = "Credit Card";
                break;
            case 2:
                method = "Debit Card";
                break;
            case 3:
                method = "Bank Transfer";
                break;
            case 4:
                method = "Digital Wallet";
                break;
            default:
                method = "Unknown method";
        }
        
        System.out.println("Payment method: " + method);
    }
}

Output:

textPayment method: Debit Card

ความสำคัญ: break statement

javaint x = 1;

// ❌ ไม่มี break - Fall-through
switch (x) {
    case 1:
        System.out.println("One");
        // ไม่มี break ลงไปทำ case 2 ด้วย!
    case 2:
        System.out.println("Two");
    default:
        System.out.println("Other");
}
// Output:
// One
// Two
// Other

// ✓ มี break - ถูกต้อง
switch (x) {
    case 1:
        System.out.println("One");
        break;
    case 2:
        System.out.println("Two");
        break;
    default:
        System.out.println("Other");
}
// Output:
// One

Loops: การทำซ้ำ

เหตุผลของ Loop

บ่อยครั้งต้อง ทำคำสั่งเดียวกันซ้ำๆ หลายครั้ง

ตัวอย่าง: พิมพ์เลขตั้งแต่ 1 ถึง 100

java// ❌ ไม่ใช้ loop - ต้องเขียน 100 บรรทัด!
System.out.println(1);
System.out.println(2);
System.out.println(3);
// ... ยาวมาก!

// ✓ ใช้ loop - เขียนแค่ 3 บรรทัด!
for (int i = 1; i <= 100; i++) {
    System.out.println(i);
}

1. for Loop: ทำซ้ำตามจำนวนครั้ง

for ใช้เมื่อทราบ จำนวนครั้ง ที่ต้องทำซ้ำแล้ว

โครงสร้าง for

javafor (initialization; condition; increment) {
    // ทำสิ่งนี้ซ้ำตราบที่ condition เป็น true
}

ส่วนประกอบ:

  • initialization: กำหนดค่าเริ่มต้น
  • condition: เงื่อนไขการทำซ้ำ
  • increment: เปลี่ยนค่าหลังทำแต่ละรอบ

ตัวอย่าง: พิมพ์เลข 1-5

javapublic class ForLoopDemo {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            System.out.println(i);
        }
    }
}

Output:

text1
2
3
4
5

วิธีทำงาน:

textรอบที่ 1: i=1, 1<=5? ใช่ → พิมพ์ 1, i++ (i=2)
รอบที่ 2: i=2, 2<=5? ใช่ → พิมพ์ 2, i++ (i=3)
รอบที่ 3: i=3, 3<=5? ใช่ → พิมพ์ 3, i++ (i=4)
รอบที่ 4: i=4, 4<=5? ใช่ → พิมพ์ 4, i++ (i=5)
รอบที่ 5: i=5, 5<=5? ใช่ → พิมพ์ 5, i++ (i=6)
รอบที่ 6: i=6, 6<=5? ไม่ → ออกจาก loop

ตัวอย่าง: คำนวณผลรวม

javapublic class SumCalculator {
    public static void main(String[] args) {
        int sum = 0;
        
        for (int i = 1; i <= 10; i++) {
            sum += i;  // sum = sum + i
        }
        
        System.out.println("Sum from 1 to 10: " + sum);
    }
}

Output:

textSum from 1 to 10: 55

ตัวอย่าง: ตารางสูตรคูณ

javapublic class MultiplicationTable {
    public static void main(String[] args) {
        int number = 5;
        
        System.out.println("Multiplication table of " + number);
        
        for (int i = 1; i <= 12; i++) {
            System.out.printf("%d x %d = %d\n", number, i, number * i);
        }
    }
}

Output:

textMultiplication table of 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
...
5 x 12 = 60

for loop ลดลง

javapublic class ReverseLoop {
    public static void main(String[] args) {
        for (int i = 5; i >= 1; i--) {
            System.out.println(i);
        }
    }
}

Output:

text5
4
3
2
1

2. while Loop: ทำซ้ำตามเงื่อนไข

while ใช้เมื่อ ไม่ทราบจำนวนครั้ง แต่ทราบเงื่อนไขการหยุด

โครงสร้าง while

javawhile (condition) {
    // ทำสิ่งนี้ซ้ำตราบที่ condition เป็น true
}

ตัวอย่าง: พิมพ์เลข 1-5

javapublic class WhileLoopDemo {
    public static void main(String[] args) {
        int i = 1;
        
        while (i <= 5) {
            System.out.println(i);
            i++;
        }
    }
}

Output:

text1
2
3
4
5

ตัวอย่าง: รับข้อมูลจนกว่า user พอ

javaimport java.util.Scanner;

public class WhileInputDemo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int sum = 0;
        int number;
        
        System.out.println("Enter numbers (enter -1 to stop):");
        
        while (true) {
            System.out.print("Enter number: ");
            number = input.nextInt();
            
            if (number == -1) {
                break;  // ออกจาก loop
            }
            
            sum += number;
        }
        
        System.out.println("Total sum: " + sum);
        input.close();
    }
}

Output (ตัวอย่าง):

textEnter numbers (enter -1 to stop):
Enter number: 10
Enter number: 20
Enter number: 30
Enter number: -1
Total sum: 60

ตัวอย่าง: ตรวจสอบ Password

javaimport java.util.Scanner;

public class PasswordValidator {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String correctPassword = "java123";
        String enteredPassword = "";
        
        while (!enteredPassword.equals(correctPassword)) {
            System.out.print("Enter password: ");
            enteredPassword = input.nextLine();
            
            if (!enteredPassword.equals(correctPassword)) {
                System.out.println("Wrong password! Try again.");
            }
        }
        
        System.out.println("Login successful!");
        input.close();
    }
}

Output:

textEnter password: wrong
Wrong password! Try again.
Enter password: java123
Login successful!

3. do-while Loop: ทำก่อน แล้วค่อยตรวจสอบ

do-while คล้ายกับ while แต่ ทำอย่างน้อย 1 ครั้งเสมอ

โครงสร้าง do-while

javado {
    // ทำสิ่งนี้
} while (condition);

ตัวอย่าง:

javapublic class DoWhileDemo {
    public static void main(String[] args) {
        int i = 1;
        
        do {
            System.out.println(i);
            i++;
        } while (i <= 5);
    }
}

Output:

text1
2
3
4
5

ความแตกต่าง while vs do-while

java// while - ตรวจสอบก่อน
int x = 10;
while (x < 5) {
    System.out.println(x);  // ไม่ทำเลย (10 < 5 เป็น false)
}

// do-while - ทำก่อน แล้วค่อยตรวจสอบ
int y = 10;
do {
    System.out.println(y);  // ทำ 1 ครั้ง (แล้วค่อยตรวจสอบ)
} while (y < 5);

ตัวอย่าง: ระบบเมนูแบบวนซ้ำ

javaimport java.util.Scanner;

public class MenuSystem {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int choice;
        
        do {
            System.out.println("\n=== Main Menu ===");
            System.out.println("1. Add");
            System.out.println("2. Subtract");
            System.out.println("3. Multiply");
            System.out.println("0. Exit");
            System.out.print("Enter choice: ");
            choice = input.nextInt();
            
            switch (choice) {
                case 1:
                    System.out.println("Addition selected");
                    break;
                case 2:
                    System.out.println("Subtraction selected");
                    break;
                case 3:
                    System.out.println("Multiplication selected");
                    break;
                case 0:
                    System.out.println("Goodbye!");
                    break;
                default:
                    System.out.println("Invalid choice!");
            }
        } while (choice != 0);
        
        input.close();
    }
}

Output:

text=== Main Menu ===
1. Add
2. Subtract
3. Multiply
0. Exit
Enter choice: 1
Addition selected

=== Main Menu ===
1. Add
2. Subtract
3. Multiply
0. Exit
Enter choice: 0
Goodbye!

Loop Control: ควบคุมการ Loop

break: ออกจาก Loop

break ใช้เพื่อ ออกจาก loop โดยทันที

javafor (int i = 1; i <= 10; i++) {
    if (i == 5) {
        break;  // ออกจาก loop เมื่อ i == 5
    }
    System.out.println(i);
}

Output:

text1
2
3
4

continue: ข้ามไปรอบต่อไป

continue ใช้เพื่อ ข้ามคำสั่งที่เหลือของรอบนี้และไปรอบต่อไป

javafor (int i = 1; i <= 5; i++) {
    if (i == 3) {
        continue;  // ข้าม i=3
    }
    System.out.println(i);
}

Output:

text1
2
4
5

ตัวอย่าง: หาเลขคี่

javapublic class OddNumbers {
    public static void main(String[] args) {
        System.out.println("Odd numbers from 1 to 10:");
        
        for (int i = 1; i <= 10; i++) {
            if (i % 2 == 0) {
                continue;  // ข้ามเลขคู่
            }
            System.out.println(i);
        }
    }
}

Output:

textOdd numbers from 1 to 10:
1
3
5
7
9

Nested Loops: Loop ซ้อน Loop

บ่อยครั้ง loop ซ้อนอยู่ในอีก loop หนึ่ง

ตัวอย่าง: สี่เหลี่ยมตัวอักษร

javapublic class Rectangle {
    public static void main(String[] args) {
        int rows = 3;
        int cols = 5;
        
        for (int i = 1; i <= rows; i++) {
            for (int j = 1; j <= cols; j++) {
                System.out.print("* ");
            }
            System.out.println();  // ขึ้นบรรทัดใหม่
        }
    }
}

Output:

text* * * * *
* * * * *
* * * * *

ตัวอย่าง: ตาราง

javapublic class MultiplicationTable {
    public static void main(String[] args) {
        System.out.println("Multiplication Table (1x1 to 5x5):");
        System.out.println();
        
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= 5; j++) {
                System.out.printf("%3d ", i * j);
            }
            System.out.println();
        }
    }
}

Output:

textMultiplication Table (1x1 to 5x5):

  1   2   3   4   5
  2   4   6   8  10
  3   6   9  12  15
  4   8  12  16  20
  5  10  15  20  25

ตัวอย่าง: สามเหลี่ยม

javapublic class Triangle {
    public static void main(String[] args) {
        int n = 5;
        
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print("* ");
            }
            System.out.println();
        }
    }
}

Output:

text*
* *
* * *
* * * *
* * * * *

สรุป: Control Flow

โครงสร้างการใช้ตัวอย่าง
if-elseตัดสินใจ 2 ทางif (age >= 18) { ... } else { ... }
if-else if-elseตัดสินใจหลายทางif (...) { } else if (...) { }
switchเลือก 1 จาก หลายค่าswitch (day) { case 1: ... break; }
forทำซ้ำตามจำนวนfor (int i=1; i<=10; i++) { }
whileทำซ้ำตามเงื่อนไขwhile (condition) { }
do-whileทำอย่างน้อย 1 ครั้งdo { } while (condition);
breakออกจาก loopif (i==5) break;
continueข้ามไปรอบต่อไปif (i==3) continue;

ตัวอย่างการใช้ทั้งหมดรวมกัน

javaimport java.util.Scanner;

public class GradeCounter {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int numStudents;
        int countA = 0, countB = 0, countC = 0, countD = 0, countF = 0;
        
        // รับจำนวนนักศึกษา
        System.out.print("Enter number of students: ");
        numStudents = input.nextInt();
        
        // Loop รับคะแนนแต่ละนักศึกษา
        for (int i = 1; i <= numStudents; i++) {
            System.out.print("Enter score for student " + i + ": ");
            int score = input.nextInt();
            
            // ตัดสินใจเกรด
            String grade;
            if (score >= 80) {
                grade = "A";
                countA++;
            } else if (score >= 70) {
                grade = "B";
                countB++;
            } else if (score >= 60) {
                grade = "C";
                countC++;
            } else if (score >= 50) {
                grade = "D";
                countD++;
            } else {
                grade = "F";
                countF++;
            }
            
            System.out.println("Score: " + score + " → Grade: " + grade);
        }
        
        // แสดงสรุป
        System.out.println("\n=== Grade Summary ===");
        System.out.println("A: " + countA);
        System.out.println("B: " + countB);
        System.out.println("C: " + countC);
        System.out.println("D: " + countD);
        System.out.println("F: " + countF);
        
        input.close();
    }
}

Output (ตัวอย่าง):

textEnter number of students: 5
Enter score for student 1: 85
Score: 85 → Grade: A
Enter score for student 2: 75
Score: 75 → Grade: B
Enter score for student 3: 60
Score: 60 → Grade: C
Enter score for student 4: 90
Score: 90 → Grade: A
Enter score for student 5: 55
Score: 55 → Grade: D

=== Grade Summary ===
A: 2
B: 1
C: 1
D: 1
F: 0