1 / 87

Java Control Flow Statements

ทฤษฎีครั้งที่ 3. Java Control Flow Statements. Control Structures. sequence structure selection structure repetition structure. Control Structures. Sequential execution Program statements execute one after the other Transfer of control

ksloan
Download Presentation

Java Control Flow Statements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ทฤษฎีครั้งที่ 3 Java Control Flow Statements

  2. Control Structures • sequence structure • selection structure • repetition structure

  3. Control Structures • Sequential execution • Program statements execute one after the other • Transfer of control • Three control statements can specify order of statements • Sequence structure • Selection structure • Repetition structure

  4. Control Flow Statements selection • if • switch • while • for • do-while • break • continue • return repetition

  5. Flowlines Action Symbols Connector Symbols add grade to total total = total + grade; add 1 to counter counter = counter + 1 ; • Fig 4.1 Flowcharting Java’s sequence structure.

  6. Selection Structures • Java has a sequence structure “built-in” • Java provides three selection structures • if • if/else • switch • Java provides three repetition structures • while • do/while • do

  7. The if Statement syntax: if (booleanExpression)statement eg. if (quantity > 10) discountPercent = 15;

  8. import javax.swing.JOptionPane; class If1 { public static void main (String args[]) { int score = 50; if (score > 0) { String message = "score = " + score + "grade = pass" ; JOptionPane.showMessageDialog(null,message); System.exit(0); } } }

  9. The if/else Selection Structure • Perform action only when condition is true • Perform different specified action when condition is false • Conditional operator (?:) • Nested if/else selection structures

  10. if statement • Syntax: if statement with two alternatives • (if-else) if (condition) statementT else statementF true false condition statementT statementF if ( count > 0 ) average = sum / count; else average = 0.0; System.out.println (average);

  11. Nested if-else and switch statements Simple if-else format if (condition) statementT else statementF Nested if -else format if (condition1 ) if (condition2 ) statementT2 else statementF2 else if (condition3 ) statementT3 else statementF3 Matching rule: in a nested if-else statement, an else is matched with the closest preceding if that is not matched yet. if ( x > 0 ) if (y > 0) { z = sqrt (x) + sqrt (y); System.out.println(“z = “ + z); } else System.out.println( “*** can’t compute z”);

  12. Multiple-alternative selection Nested if -else format if (condition1 ) statement1 else if (condition2 ) statement2 else if (condition3 ) statement3 else if (conditionn ) statementn else statementn+1 . . . • Multiple-alternative selection: choose exactly one alternative out of more than two mutually-exclusive alternatives. • Implementation: either as a nested if-else structure (where new decisions fall on else branches), or as an equivalent if-else if structure. Equivalent if -else if format if (condition1 ) statement1 elseif (condition2 ) statement2 else if (condition3 ) statement3 else if else if (conditionn ) statementn else statementn+1 . . .

  13. neutral very acidic acidic alkaline very alkaline pH 3 7 12 if (pH < 3) System.out.println( "Solution is very acidic.”); else if (pH < 7) System.out.println( "Solution is acidic.”); else if (pH == 7) System.out.println(”Solution is neutral."); else if(pH < 12) System.out.println( "Solution is alkaline.”); else System.out.println( "Solution is very alkaline.”); Example of multiple-alternative selection Solution pH: true pH < 3 false very acidic pH>=3 true pH<7 false acidic pH>=7 true pH ==7 false neutral pH >7 if (pH >=12) System.out.println( "Solution is very alkaline.”); else if (pH >7) System.out.println( "Solution is alkaline.”); else if (pH ==7) System.out.println(”Solution is neutral."); else if (pH >=3) System.out.println( "Solution is acidic.”); else System.out.println( "Solution is very acidic.”); true pH<12 false alkaline pH>=12 very alkaline

  14. import javax.swing.JOptionPane; class If2 { public static void main (String args[]) { double score ;String message,data; data = JOptionPane.showInputDialog(null,"Enter score : "); score = Double.parseDouble(data); if (score >= 49) message = "score = " + score + "grade = Pass"; else message = "score = " + score + "grade = F" ; JOptionPane.showMessageDialog(null,message); System.exit(0); } }

  15. Example if-else class IfElseDemo { public static void main(String[] args) { int testscore = 76; char grade; if (testscore >= 90 ) { grade = 'A'; } else if (testscore >= 80 ) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; } System.out.println(“Grade = “ + grade); } }

  16. import javax.swing.JOptionPane; class If22 { public static void main (String [ ]args) { int score ;String message,data; data = JOptionPane.showInputDialog(null,"Enter score : "); score = Integer.parseInt(data); if (score >= 49) message = "score = " + score + "grade = Pass"; else message = "score = " + score + "grade = F" ;

  17. JOptionPane.showMessageDialog(null,message); System.exit(0); System.out.println("score = "+score); } }

  18. if – elseและ block statement class IfElse3 { public static void main(String args[ ] ) { int Target = 10000000; int TotalSale = 12345678; int Salary = 20000; System.out.println( "Your total sale amount last year was " + TotalSale); if ( TotalSale >= Target ) { System.out.println("Congratulation! “ + “Your target have been met." + " You are promoted."); Salary += Salary * 20/100; } else Salary += Salary * 5/100; System.out.println("Your new salary is " + Salary ); } }

  19. Switch statement • Interpretation: • value of selectoris evaluated and compared to each label in turn • when a matching label is found, the statements that follow that label are executed until a break or a return statement is reached;all the other statements in the switch block are skipped • if no matching label is found, the statements following default are executed. • default clause is optional; if it’s missing, no statement is executed in the cases when no matching label was found. • if a break (return) statement is missing, execution “falls through” to the statements associated with the next set of labels. Type of selector and of labels • must be an ordinal type (in Java, ordinal types are: integer types, bool and char) • cannot bea floating point type, nor a string of characters • each label must be a unique value of the same type as the selector Switch statement syntax: switch (selector) { case label11: case label12: . . . case label1k:statements1 break; . . . case labeln1: case labeln2: . . . case labelnm:statementsn break; default: statementsd }

  20. คำสั่ง switch (The switch Statement) ข้อจำกัดของการใช้คำสั่ง Switch ตัวแปรที่ใช้ในการตรวจสอบ จะต้องมีชนิดเป็นตัวเลขอย่างใดอย่างหนึ่ง ได้แก่ char, byte, short หรือ int มักจะถูกใช้บ่อยในกรณีของการเลือกหนึ่งทางเลือกในหลายๆทางเลือก Switch: switch (ตัวแปร) { case ค่าที่ 1 : คำสั่งที่ 1; break; case ค่าที่ 2 : คำสั่งที่ 2; break; . . case ค่าที่ N : คำสั่งที่ N; break; default : คำสั่งเมื่อไม่มีค่าที่ตรงกับที่ระบุใน case ; }

  21. same effect same effect Switch statement examples // Set price for a light bulb of // 40, 60, 75, 100 or 150 watts switch (watts) { case40: price = 0.50; break; case60: price = 0.69; break; case75: price = 0.85; break; case 100: case150: price = 1; break; default: price = 0; System.out.print (“No bulb ” +watts + “watts in stock”); } // end switch if (watts == 40) price = 0.50; elseif (watts== 60) price = 0.69; elseif (watts == 75) price = 0.85; elseif (watts == 100 || watts==150) price = 1; else { price = 0; System.out.print (“No bulb ”+watts + “watts in stock”); }

  22. public class SwitchDemo { public static void main(String[] args) { int month = 8; switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; } } }

  23. Example switch class SwitchDemo2 { public static void main(String[] args) { int day = 7; switch (day) { case 1: System.out.println(“Monday"); break; case 2: System.out.println(“Tuesday"); break; case 3: System.out.println(“Wednesday"); break; case 4: System.out.println(“Thursday"); break; case 5: System.out.println(“Friday"); break; case 6: System.out.println(“Saturday"); break; case 7: System.out.println(“Sunday"); break; } } }

  24. while statement in while loop true (condition) false The while Statement Flowchart

  25. initialization false condition true statement exit the loop Loops: while statement part of the loop not contained in the while stmt. Format while (condition) statement • A while statement implements a pre-test loop which is repeated as long as the condition is true. • The repetition ends when the condition is found to be false, and the execution continues with the statement that follows the loop body. • The body of the loop must eventually cause the condition to become false, otherwise an infinite loop results. • The loop body is a simple or a compound statement. • a while loop may be executed zero times if the condition is found false when tested for the first time. repeat the loop Important: do not confuse the while statement (a loop) with the if statement (a selection which does not imply any repetition).

  26. Accumulating a sum int next; // the next number int sum= 0; // the sum so far int count = 0; // initialize loop counter while (count < MAX) { // test loop counter readInt(next); // get next number sum = sum + next; // add next number to sum count = count + 1; // increment loop counter } // end loop Trace of while loop next sum count after initialization ? 0 0 sum and count set to 0, next undefined after 1st iter. 15 15 1 15 read into next and added to sum after 2nd iter. 20 35 2 20 read into next and added to sum after 3rd iter. -5 30 3 -5 read into next and added to sum, . . .

  27. Example public class Series { public static void main (String[] args) { int x = 1; int total = 0; while (x <= 100) { total += x; x = x + 1; } System.out.println ("The series from 1 to 100 is " + total); } }

  28. ตัวอย่างการคำนวณดอกเบี้ยตัวอย่างการคำนวณดอกเบี้ย int year = 0; double balance = 100; while (balance <= 10000) { year++; balance *= 1.05; }

  29. do - while flowchart

  30. do-while • syntax do { statement; } while(expression); • The Statement is executed, and then the boolean typed expression is evaluated. If it is false, execution drops through to the next statement. If it is true, you loop through the Statement again. • This form of loop is for iterations that take place at least one time. If the Expression is false on the first evaluation, the Statement will already have execute once

  31. do-while example class DoWhile { public static void main(String args[]) { int count=0; do { count++; System.out.println(count); } while (count < 20); } }

  32. public class Testdo { publicstatic void main (String args[]) {int data =1; int sum = 0; do { sum += data ; data = data+1; System.out.println ("data = " +data+" Sum : " + sum) ; } while (data <=10) ; System.out.println("========================="); System.out.println ("data = " +(data-1)+" Sum : " + sum) ; } } // Testdo

  33. initialization (expression 1 ) for statement condition increment Yes in (expression 2) (expression 3) loop No for ( expression1; condition; expression3 ) statement ; The for Statement

  34. initialization of loop control variable false condition true loop body update loop control variable exit the loop for statement Format for (initialization;condition; update) statement • A for loop is a loop structure which is mainly used to implement counter-controlled loops • a for loop may be executed zero times if the condition is false when first tested • Example:two equivalent counter-controlled loops: one with for and the other with while for (int i = initial ; i <=final; i = i+step) { // insert loop body here } var i defined only inside the loop body int i = initial ; while (i <=final) { // insert loop body here i = i + step; }

  35. for (ค่าตัวแปรเริ่มต้น ; เงื่อนไข ; เปลี่ยนแปลงค่าของตัวเลข ) { คำสั่งต่าง ๆ ; } for ( count = 0 ; count <=10 ; count ++ ) { System.out.println("*");}

  36. The for Statement for (initStmt; boolExpr; incrExpr) statement eg. int sum=0; for (int x = 2; x <= 10; x+=2) sum += x; System.out.println(sum);

  37. class For1 { public static void main(String[] args) { int i; int sum = 0; for (i=1;i<=10 ;i++ ) { sum+=i; System.out.println(" i = "+i+"sum = " + sum); } System.out.println("sum 1+2+....."+(i-1)+" = "+sum); } }

  38. ตัวอย่างการคำนวณยอดเงินในบัญชีเมื่อเวลาผ่านไป 95 ปี double balance = 100; for (int i = 0; i < 95; i++) { balance *= 1.05; } System.out.println(balance);

  39. คำสั่ง break

  40. The break Statement breaklabelopt; class Break { public static void main(String args[]) { for (int x=0; x < 5; x++) { if (x == 3) break; System.out.println(i); } System.out.println(“End”); }

  41. การออกจาก while ด้วยคำสั่ง break while( เงื่อนไข ในการวนลูป) { …. if( เงื่อนไขที่จะออกจากลูป ) break; …. } คำสั่งหลังลูป;

  42. การออกจาก for ด้วยคำสั่ง break for (int i = 0; i < 5; i++) { System.out.print("<"); if (i == 2) break; System.out.print(i + ">"); }

  43. ตัวอย่าง class Switch { publicstaticvoid main(String[] args) { int x=1000; int value=4; switch (value) { case 1 : x+=20; break; case 3 : x+=450; break; case 4 : x+=48; break; case 8 : x-=20; break; default: x+=10; break; } System.out.println("x = " + x); } }

  44. class BreakDemo { public static void main(String args[]) { boolean inloop = true;int n = 2; Outer: while (inloop) { Middle: while (inloop) { Inner: while (inloop){ System.out.println("Inner Block"); inloop = false; // disable repetition if ( n == 0 ) break; if ( n == 1 ) break;//Inner if ( n == 2 ) break;//Middle if ( n == 3 ) break;//Outer } System.out.println("Middle Block"); } System.out.println("Outer Block"); } System.out.println(“Not in loop”); } } ตัวอย่างโปรแกรมแสดงการใช้ break - label

  45. คำสั่ง continue

  46. The continue Statement continuelabelopt; class Continue1 { pubic static void main(String[] args) { for (int i=0; i < 5; i++) { if (i == 3) continue; System.out.println(i); } System.out.println(“End”); } }

  47. ข้ามไปตรวจสอบเงื่อนไขข้ามไปตรวจสอบเงื่อนไข while( เงื่อนไขในการวนลูป) { …. if( เงื่อนไขที่จะกลับไปต้นลูป ) continue; …. }

  48. ข้ามไปตรวจสอบเงื่อนไขข้ามไปตรวจสอบเงื่อนไข for (ประโยคเริ่ม; เงื่อนไข; ประโยคอัพเดท) { …. if( เงื่อนไขที่จะกลับไปต้นลูป ) continue; …. }

  49. ตัวอย่างโปรแกรม for (int i = 0; i < 5 ; i++ ) { System.out.print("<"); if (i == 2) continue; System.out.print(i + ">"); }

  50. The return Statement returnexpressionopt; The return statement is used in methods to exit from the method. It is also used to return a value from the method that is supposed to return a value.

More Related