1 / 29

Computer Programming with Java

Computer Programming with Java . Chapter 3 Flow of Control. Contents. Overview Branching Statements Loop Statements Programming with Loops. Overview. Flow of control the order in which actions are performed by your program. Branching statements

haley
Download Presentation

Computer Programming with Java

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. Computer Programming with Java Chapter 3 Flow of Control

  2. Contents • Overview • Branching Statements • Loop Statements • Programming with Loops

  3. Overview • Flow of control • the order in which actions are performed by your program. • Branching statements • choose one action from a list of two or more possible actions • Loop statements • repeats some action again and again until some stopping condition is met

  4. Branching Statements • The if-else- statement if (Boolean_Expression) statement_1 else statement_2 If the Boolean_Expression is true, then Statement_1 is executed; otherwise, Statement_2 is executed. if (Boolean_Expression) statement_1

  5. public class BankBalance { public static final double OVER_DRAWN_PENALTY = 8.00; public static final double INTEREST_RATE = 0.02;//2% annually public static void main(String[] args) { double balance; System.out.print("Enter your checking account balance: $"); balance = SavitchIn.readLineDouble(); System.out.println("Original balance $" + balance); if (balance >= 0) balance = balance + (INTEREST_RATE * balance)/12; else balance = balance - OVER_DRAWN_PENALTY; System.out.println("After adjusting for one month"); System.out.println("of interest and penalties,"); System.out.println("your new balance is $" + balance); } } Display 3.1: A Program using if-else

  6. Branching Statements (1) • Comparison Operators

  7. public class StringEqualityDemo{ public static void main(String[] args){ String s1, s2; System.out.println("Enter two lines of text:"); s1 = SavitchIn.readLine(); s2 = SavitchIn.readLine(); if (s1.equals(s2)) System.out.println("The two lines are equal."); else System.out.println("The two lines are not equal."); if (s2.equals(s1)) System.out.println("The two lines are equal."); else System.out.println("The two lines are not equal."); if (s1.equalsIgnoreCase(s2)) System.out.println("But, the lines are equal ignoring case."); else System.out.println("Lines are not equal even ignoring case."); } } Display 3.3: Testing Strings for Equality

  8. Branching Statements (2) • Boolean Expression • an expression that is either true or false. • “and”: && • When you form a larger boolean expression by connecting two smaller expression with &&, the entire larger expression is trueprovided that both of the smaller expressions are true. • (sub_expression1)&& (sub_expression2) • e.g.) if ((pressure > min) && (pressure < max)) System.out.println(“Pressure is OK.”); else System.out.println(“Warning: Pressure is out of range.”);

  9. Branching Statements (3) • “or” • the meaning is essentially the same as the word “or” • (sub_expression1)|| (sub_expression2) • e.g.) if ((salary > expenses) || (savings > expenses)) System.out.println(“Solvent.”); else System.out.println(“Bankrupt.”);

  10. && (and) || (or) ! (not) Display 3.12: Truth tables for boolean operators

  11. Branching Statements (4) • Nested statements • an if-else statement contains two smaller statements within it. • Compound statements • these statements formed by enclosing a list of statements within curly brackets. • Rule of thumb • To eliminate some confusion in the nested if-else statements, you had better use curly brackets to group things.

  12. Nested statements if (balance >= 0) if (INTEREST_RATE >= 0) balance = balance + (INTEREST_RATE * balance)/12; else System.out.println(“Cannot have a negative interest.”); else balance = balance - OVER_DRAWN_PENALTY; Compound statements if(balance >= 0){ System.out.println(“Good for you. You earned interest.”); balance = balance + (INTEREST_RATE * balance) /12; }else{ System.out.println(“You will be charged a penalty.”); balance = balance - OVER_DRAWN_PENALTY; }

  13. Branching Statements (4) • Multibranch if-else statements • you can use nested if-else statements to produce multiway branches that branch into any number of possibilities. If ( Boolean_Expression1) Action1 else if ( Boolean_Expression2) Action2 … else if ( Boolean_Expression n) Action n else Default_Action if (balance >= 0) System.out.println(“Positive balance.”); else if (balance < 0) System.out.println(“Negative balance.”); else if (balance == 0) System.out.println(“Zero balance.”);

  14. public class Grader{ public static void main(String[] args){ int score; char grade; System.out.println("Enter your score: "); score = SavitchIn.readLineInt(); if (score >= 90) grade = 'A'; else if (score >= 80) grade = 'B'; else if (score >= 70) grade = 'C'; else if (score >= 60) grade = 'D'; else grade = 'F'; System.out.println("Score = " + score); System.out.println("Grade = " + grade); } } Display 3.4: Multibranch if-else-Statement

  15. Branching Statements (5) • The switch statement • a multiway branch that makes its decision on which way to branch based on the value of an integer or character expression switch (Controlling_Expression){ case Case_Label: statement; … break; case Case_Label: statement; … break; … default: statement; … break; }

  16. public class MultipleBirths{ public static void main(String[] args){ int numberOfBabies; System.out.print("Enter number of babies: "); numberOfBabies = SavitchIn.readLineInt(); switch (numberOfBabies){ case 1: System.out.println("Congratulations."); break; case 2: System.out.println("Wow. Twins."); break; case 3: System.out.println("Wow. Triplets."); break; case 4: case 5: System.out.println("Unbelieveable."); System.out.println(numberOfBabies + " babies"); break; default: System.out.println("I don't believe you."); break; } } } Display 3.5: A switch-Statement

  17. Loop Statements • Program often need to repeat some action. • Terminology • loop: A portion of a program that repeats a statement or group of statements • body: the statement (or group of statements) to be repeated in a loop • iteration: each repetition of the loop body • infinite loop: A loop that iterates its body repeatedly without ever ending • see text p116.

  18. General structure of a Loop • initializing statements • loop body • mechanism for ending the loop • Rule of thumb • When you design a loop, you need to determine what action the body of the loop will take and you need to determine a mechanism for deciding when the loop should stop repeating the loop body. • How do you decide whether to use one of loop statements? • See text p 124: Choosing a Loop statement

  19. Loop Statements (1) • while statements • repeats its action again and again until a controlling boolean expression becomes false. • Note that the body of a while-loop can be executed zero times. while(Boolean_Controlling_Expression){ Body } The Body may be either a simple statement or more likely, a compound statement consisting of a list of statements enclosed in curly brackets {}.

  20. public class WhileDemo { public static void main(String[] args) { int count, number; System.out.println("Enter a number"); number = SavitchIn.readLineInt(); count = 1; while (count <= number) { System.out.print(count + ", "); count++; } System.out.println(); System.out.println("Buckle my shoe."); } } Display 3.6: A while-Loop

  21. Loop Statements (2) • do-while statement • very similar to the while-statement, but the loop body of do-while statement is always executed at least once. do { Body }while(Boolean_Controlling_Expression); The Body may be either a simple statement or more likely, a compound statement consisting of a list of statements enclosed in curly brackets {}.

  22. public class DoWhileDemo { public static void main(String[] args) { int count, number; System.out.println("Enter a number"); number = SavitchIn.readLineInt(); count = 1; do { System.out.print(count + ", "); count++; }while (count <= number); System.out.println(); System.out.println("Buckle my shoe."); } } Display 3.7: A do-while-Loop

  23. public class BugTrouble{ public static final double GROWTH_RATE = 0.95;//95% per week public static final double ONE_BUG_VOLUME = 0.002;//cubic feet public static void main(String[] args){ System.out.println("Enter the total volume of your house"); System.out.print("in cubic feet: "); double houseVolume = SavitchIn.readLineDouble(); System.out.println("Enter the estimated number of"); System.out.print("roaches in your house:"); int startPopulation = SavitchIn.readLineInt(); int countWeeks = 0; double population = startPopulation; double totalBugVolume = population*ONE_BUG_VOLUME; while (totalBugVolume < houseVolume){ population = population + (GROWTH_RATE*population); totalBugVolume = population*ONE_BUG_VOLUME; countWeeks++; } Display 3.8: Roach Population Program

  24. System.out.println("Starting with a roach population of ” + startPopulation); System.out.println("and a house with a volume of " + houseVolume + " cubic feet,"); System.out.println("after " + countWeeks + " weeks,"); System.out.println("the house will be filled"); System.out.println("floor to ceiling with roaches."); System.out.println("There will be " + (int)population + " roaches."); System.out.println("They will fill a volume of " + (int)totalBugVolume + " cubic feet"); System.out.println("Better call Debugging Experts Inc."); } }

  25. Loop Statements (3) • for-statement • a specialized loop statement that allows you to easily convert pseudocode (see text p. 129) for(Initializing_Action; Boolean_Expression; Action_After_Each_Iteration){ Body } The Body may be either a simple statement or more likely, a compound statement consisting of a list of statements enclosed in curly brackets Do the following for each value of count from 1 to 3: System.out.println(count); System.out.println(“Go”);

  26. public class ForDemo { public static void main(String[] args) { int countDown; for (countDown = 3; countDown >= 0; countDown--) { System.out.println(countDown); System.out.println("and counting."); } System.out.println("Blast off!"); } } Display 3.9: A for-statement

  27. Loop Statements (4) • break-statement • if you want to end a loop in the middle of the loop body • exit Method • an invocation of the exit method ends the program. • 0: a normal termination • 1: abnormal termination • e.g.) System.exit(0);

  28. public class BreakDemo{ public static void main(String[] args) { int itemNumber; double amount, total; System.out.println("You may buy ten items, but"); System.out.println("the total price must not exceed $100."); total = 0; for (itemNumber = 1; itemNumber <= 10; itemNumber++) { System.out.print("Enter cost of item #" + itemNumber + ": $"); amount = SavitchIn.readLineDouble(); total = total + amount; if (total >= 100) { System.out.println("You spent all your money."); break; } System.out.println("Your total so far is $" + total); System.out.println("You may purchase up to "+ (10 - itemNumber) + "more items."); } System.out.println("You spent $" + total); } } Display 3.10: Ending a loop with a break-statement

More Related