คำสั่งควบคุม Control Statement แบบทำซ้ำ ถูกนำมาใช้เพื่อช่วยในกรณี เมื่อโปรแกรมจำเป็นต้องทำงานคำสั่งเดิมซ้ำๆ
ตัวอย่างการเขียนโปรแกรมแสดงผลเปอร์เซ็นต์การ Loading บนหน้าจอเพิ่มขึ้นทีละ 10%
เมื่อไม่ใช้ Control Statement แบบทำซ้ำ
System.out.println("Loading 0%");
System.out.println("Loading 10%");
System.out.println("Loading 20%");
System.out.println("Loading 30%");
System.out.println("Loading 40%");
System.out.println("Loading 50%");
System.out.println("Loading 60%");
System.out.println("Loading 70%");
System.out.println("Loading 80%");
System.out.println("Loading 90%");
System.out.println("Loading 100%");
เมื่อใช้ Control Statement แบบทำซ้ำ while
int count = 0;
while (count <= 100) { // ทำงานภายใน while loop เมื่อเงื่อนไขเป็นจริง
System.out.println("Loading " + count + "%");
count = count + 10;
}
สังเกตุว่าจำนวนบรรทัดที่เขียน source code จะลดลงมาก เมื่อใช้ Control Statement แบบทำซ้ำ ต่อมาเรามาทำความเข้าใจวิธีการใช้ while กันครับ
Control Statement แบบทำซ้ำ while
การทำงานของ while คือ ถ้าเงือนไขภายใน while เป็นจริง (true) คำสั่งภายใน while จะทำงานซ้ำไปเรื่อยๆ จนกว่า เงือนไขภายใน while จะเป็นเท็จ (false) แสดงลักษณะเป็น Flow chart ดังตัวอย่างด้านล่าง
แสดงเป็น Source Code
while (condition) { // ทำงาน while loop เมื่อ condition เป็นจริง (true)
statement;
}
ตัวอย่างโปรแกรมหาคะแนนเฉลี่ยของนักเรียนจำนวน 10 คน ด้วยการใช้ while loop
Source Code
import java.util.Scanner;
public class ClassAverage {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Welcome to the grade book for");
System.out.println("Share.OlanLab.Com Course - Java Programming!");
int total;
int gradeCounter;
int grade;
int average;
total = 0;
gradeCounter = 1;
while (gradeCounter <= 10) {
System.out.print("Enter grade: ");
grade = input.nextInt();
total = total + grade;
gradeCounter = gradeCounter + 1;
}
average = total / 10;
System.out.printf("\nTotal of all 10 grades is %d\n", total);
System.out.printf("Class average is %d\n", average);
}
}
Output
Welcome to the grade book for
Share.OlanLab.Com Course - Java Programming!
Enter grade: 60
Enter grade: 81
Enter grade: 99
Enter grade: 100
Enter grade: 66
Enter grade: 59
Enter grade: 87
Enter grade: 96
Enter grade: 78
Enter grade: 80
Total of all 10 grades is 806
Class average is 80
บทความถัดไป
สอน Java ตอนที่ 7.2 Control Statement แบบทำซ้ำ do ... while