1. 976-140 Object-Oriented Programming
344-202 Introduction to OOP
การโปรแกรมเชิงวัตถุ
6. Flow Control
Faculty of Technology and Environment
Prince of Songkla University, Phuket Campus
2/2551
8. Try this!
5
0
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TestDemo.main(TestDemo.java:12)
Edit this program to handle with input a=5, b=0
5
0
Error: divided by zero!
Object-Oriented Programming 2/2551 8
9. Nested-If
รูปแบบที่ 3 : if ซ้อน if
Note: If จะคู่กับ else ที่อยู่ใกล้ทสุด
ี่
Object-Oriented Programming 2/2551 9
16. While
Example ต้องการพิมพ์ ************* จานวน 10 บรรทัด
กาหนด i=1 เพื่อใช้นับรอบบรรทัด
ตรวจสอบเงื่อนไขก่อนจะทาในลูป
ถ้ายังทาไม่ครบ 10 รอบก็จะพิมพ์ ****
เปลี่ยนค่า i เพื่อใช้ตรวจสอบว่า
จะทารอบถัดไปหรือไม่
Object-Oriented Programming 2/2551 16
17. Try this!
int x = 5;
int sum = 0;
i = 0;
while(i <= x)
{
sum = sum + x;
i++;
}
System.out.println(sum);
int i = 10;
while(i > 0)
{
System.out.print(i + " ");
i--;
}
Object-Oriented Programming 2/2551 17
18. Do-while
Do-while จะทางานอย่างน้อย 1 ครั้งก่อนที่จะทาการตรวจสอบเงื่อนไข
หากเงื่อนไขเป็นจริงจะทาในลูปถัดไป และจะทาจนกว่าเงื่อนไขเป็นเท็จ
Statements
true
Condition false
Example
int count = 0;
do {
System.out.println( count );
count++ ;
} while ( count < 10 );
Object-Oriented Programming 2/2551 18
19. Try this!
int y = 10;
do
{
System.out.println(y);
y += 10;
} while(y <= 100);
จงเขียนโปรแกรมแสดงเลขสุ่มที่มีค่า 1-10 จานวน 10 ตัว
โดยใช้ while loop
Object-Oriented Programming 2/2551 19
21. For
Example
for (int i = 0; i < 10; i=i+2) {
System.out.println(i);
}
for (int i = 0; i < 5; i++) {
System.out.println(i++);
}
Object-Oriented Programming 2/2551 21
22. Nested For
การใช้ For ซ้อน For จะมีการวนรอบโดยแต่ละรอบของ for ด้านนอก จะมี
การทางาน for ด้านใน
For-loop นอก ทางาน 5 รอบ โดยเพิ่มค่า i รอบละ 1
แต่ละรอบของ i จะทางานใน for-loop ใน โดยค่า j เพิ่มรอบละ 1 และทาจานวน
รอบตามเงื่อนไข
Object-Oriented Programming 2/2551 22