Presentation is loading. Please wait.

Presentation is loading. Please wait.

Control Structures Introduction Decision Statements The if Construct The if.. else Construct The switch Statement Iterative Constructs The while Construct.

Similar presentations


Presentation on theme: "Control Structures Introduction Decision Statements The if Construct The if.. else Construct The switch Statement Iterative Constructs The while Construct."— Presentation transcript:

1 Control Structures Introduction Decision Statements The if Construct The if.. else Construct The switch Statement Iterative Constructs The while Construct The do.. while Construct The for Construct

2 Control Structures Objectives To understand what control structures are and the need for them To establish and understand the three categories of program control flow – selection, iteration and exception. To understand selection statements – if and switch - as means of controlling the program flow. To understand iterative statements – while, do/while, and for as means of controlling the program flow.

3 Control Structures Program statements are executed in a linear fashion, unless otherwise specified. That is: Execution begins from the first statement to the last No statement is skipped, and None is repeated The calling of methods: Does not constitute an altering of the control flow Is an expansion of the statement call – replaced by the method definition. Control structures alter the flow of the statements in a piece of code. The flow of execution can be altered a)Selection statements or b)Iterative statements.

4 Selection Statements Selection statements allow you to choose between statements The choice is based on the result of a conditional expression. There are two basic selection statements: The if statement, and The switch statement

5 The if Statement The if statement has two forms, namely: One without an alternate choice, and The other with an alternate choice The general format of an if statement without an alternate choice is as follows: if ( conditional_expression ) a_single_statement; or if ( conditional_expression ) { Two or more statements; } Interpretation - if the conditional expression evaluates to true then the statement block is executed; failing that, the block is skipped.

6 The if Statement if ( 30 > 25 ) System.out.println(“That is correct”); Note: if is the keyword, and 30 > 25 is the relational expression that is being tested. The condition is evaluated to true, and hence the print statement is executed if ( 30 > 25 ) { System.out.println(“That is correct”); System.out.println(); } The conditional expression evaluates to true, hence the statement block is executed

7 The if Statement The if statement must be viewed as one complete thought In both cases - with the single statement as well as with block of statements. if ( 30 > 25 ) System.out.println(“That is correct”); Is the same as saying: if ( 30 > 25 ) System.out.println(“That is correct”); The second case could have been written as: if ( 30 > 25 ) { System.out.println(“That is correct”); System.out.println(); }

8 Example A Florida company wants to offer scholarship to some needy students. Preference is given to Florida residence who fall in the age range of 18 years and 25 years. Write a class that accepts at minimum, the name, age, and the state of residence. Among other things, write: (a)A mutator method called checkEligibility() that determines if the student is eligible to get the scholarship, and (b)An accessor method isEligibility() that returns true/false if the individual is eligible.

9 class Scholarship { String name, state; int age; boolean florida; Scholarship(String name, int age, String state) { this.name = name; this.age = age; this.state = state; } void checkEligibility() { if ( (age >= 18 && age <= 25) && state.equalsIgnoreCase("Florida") ) florida = true; } public String toString() { return name + " is " + age + " years old" + “\n” + "This person gets a scholarship" + “\n” + "This person is a Floridian"; } boolean isEligible() { return florida; }

10 Example – Test Class 1.class TestScholarship 2.{ 3. public static void main(String[] arg) 4. { 5. Scholarship s = new Scholarship("John Brown", 20, "FLorida"); 6. 7. s.checkEligibility(); 8. 9. if ( s.isEligible() ) 10. System.out.println(s); 11. } 12.}

11 The if … else Construct The if … else construct allows for an alternate of two choices The general format is: if ( condition ) statement_1; else statement_2;

12 The if … else Construct The if … else construct allows for an alternate of many choices The general format is: if (condition_1) statement_1; else if (condition_2) statement_2; : else if (condition i ) statement i else statement;

13 Example A company wants to offer scholarship needy children. The advertisement will be nation wide but the funds will be allocated as follows: Florida residents get 50% and no age restriction Other US residents get 35% and must be 18 to 30 years old International students get 15%, and must be 18 years and 25 years old Write a class that accepts at minimum, the name, age, and the state of residence. Among other things, write: (a)A mutator method called checkEligibility() that determines if the student is eligible to get the scholarship, and if so, calculate the award per person. (b)Accessor methods that return the eligibility status per person. (c)An accessor method that returns the amount awarded per individual.

14 1.class Scholarship 2.{ 3. static final double FL = 0.5, US = 0.35, OTHER = 0.15; 4. String name, state; 5. int age; 6. 7. boolean florida, usa, international, eligible; 8. double amount, award; 9. 10. Scholarship(String name, int age, String state, double amount) 11. { 12. // Constructor definition 13. } 14. String getName(){return name;} 15. int getAge(){return age;} 16. 17. void checkEligibility() 18. { 19. // Definition 20. } 21. boolean isEligible(){return eligible;} 22. boolean isFloridaEligible(){return florida;} 23. boolean isUSAEligible(){return usa;} 24. boolean isInternationalEligible(){return international;} 25. double getAward(){return award;} 26.}

15 Constructor Definition 1.Scholarship(String name, int age, String state, double amount) 2.{ 3. this.name = name; 4. this.state = state; 5. this.amount = amount; 6. this.age = age; 7. eligible = true; 8.}

16 1.void checkEligibility() // Definition 2.{ 3. if (state.equalsIgnoreCase("Florida")) 4. { 5. florida = true; 6. award = amount * FL; 7. } 8. else if (state.equalsIgnoreCase("uSa") && age >= 18 && age <= 30) 9. { 10. usa = true; 11. award = amount * US; 12. } 13. else if(age >= 18 && age <= 25 &&state.equalsIgnoreCase("International")) 14. { 15. international = true; 16. award = amount * OTHER; 17. } 18. else 19. eligible = false; 20.}

17 1.String str = “”; 2.Scholarship s = new Scholarship("John Brown", 24, "big", 10000); 3.s.checkEligibility(); 4.if ( ! s.isEligible() ) 5. str = “This person is not eligible"; 6.else if ( s.isFloridaEligible() ) 7. str = s.getName() + " is a Floridian and gets an award of $" + s.getAward(); 8.else if ( s.isUSAEligible() ) 9.{ 10. str = s.getName() + " is " + s.getAge() + " years old“ 11. str = str + “\nThis person is a US citizen and gets an award of $" + s.getAward(); 12.} 13.else 14.{ 15. str = s.getName() + " is " + s.getAge() + " years old\n“; 16. str = str + “This person is an international student\n and gets an award of $" 17. + s.getAward(); 18.} 19.System.out.println(str);

18 Designing if/else construct 90 – 100A 80 – 89B 70 – 79C 60 – 69D 59 or belowF ScoreGrade Given the score ranges and the associated letter grade, write an if/else construct that will assign a letter grade to a given score

19 Example – Determining discounts Quantity0 – $10.0$10.01 - $20.00$20.01 & over 1 -490%1%2% 50 - 991%2%3% 100 & over2%5%10% Unit Price and Percentage Discounts A wholesale company discounts the price of its products depending on the number of units bought and the unit price per for each item. The rules for calculating discounts are shown in the table below. Write a class called Discount that accepts the number of units and the corresponding price. It validates the quantities and calculates the discount amount where possible

20 Class Discount 1.Class Discount 2.{ 3. int quantity; 4. double price; 5. 6. Discount(int quantity, double price) 7. { 8. this.quantity = quantity; 9. this.price = price; 10. } 11.}

21 Solution – Validate Quantity Boundaries Quantity0 – $10.0$10.01 - $20.00$20.01 & over 1 -490%1%2% 50 - 991%2%3% 100 & over2%5%10% Quantity boundaries 1 49 99

22 Validate Quantity 1.Class Discount 2.{ 3. int quantity; 4. double price; 5. 6. Discount(int quantity, double price) 7. { 8. this.quantity = quantity; 9. this.price = price; 10. } 11. 12. boolean quantityOutOfRange() 13. { 14. return quantity < 0; 15. } 16.}

23 Solution – Validate Price Boundaries Q1 0.0$10.00$20.00 boolean priceOutOfRange() { return price < 0; }

24 1.Class Discount 2.{ 3. int quantity; 4. double price; 5. 6. Discount(int quantity, double price) 7. { 8. this.quantity = quantity; 9. this.price = price; 10. } 11. boolean quantityOutOfRange() 12. { 13. return quantity < 0; 14. } 15. boolean priceOutOfRange() 16. { 17. return price < 0; 18. } 19.}

25 Determining discounts 1.void calculate() 2.{ 3. if (quantity > NINETY_NINE) 4. { 5.// calculate discount 6. } 7. else if (quantity > FORTY_NINE) 8. { 9. // calculate discount 10. } 11. else 12. { 13.// calculate discount 14. } 15. 16. discount_amount = discount * quantity * price; 17.}

26 Calculate discount 1.void calculate() 2.{ 3. if (quantity > NINETY_NINE) 4. { 5. if (price > TWENTY) 6. discount = TEN_PERCENT; 7. else if ( price > TEN) 8. discount = FIVE_PERCENT; 9. else 10. discount = TWO_PERCENT; 11. } 12. else if (quantity > FORTY_NINE) 13. { 14. // calculate discount 15. } 16. else 17. { 18.// calculate discount 19. } 20. 21. discount_amount = discount * quantity * price; 22.}

27 The switch statement The switch statement is a special case of the if statement. The statement test only integral types, excluding long. The statement cannot test on floating-point quantities. The general format of the switch statement is: switch (selector_variable) { case value_1: statement_1; break; case value_2: statement_2; break; : default: statement; break; }

28 Meaning The switch expression contains the integral value that is to be tested against value in the case statements. The case statement provides entry to the statement to be executed if a match is made. The default statement specifies what must to be done if no match is made. The default statement may be placed anywhere within the scope of the switch statement. The break statement terminates each case. The case-label must be unique. Two or more case-labels may share the same expression.

29 public class TheSwitch { public static void main(String arg[]) { int day = getData.getInt(“Get an integer 1 – 7”); switch (day) { case 1: case 2: case 3: System.out.println(“This is a work day"); break; case 4: System.out.println("Middle of the week”); break; case 5: System.out.println("Soon it will be weekend"); break; case 6: case 7: System.out.println(“Weekend is here!!!"); break; – default: break; }

30 An internet service provider (ISP) has three different subscriptions packages for its customers. The packages are as follows: Package A: For $9.95 per month, 10 hours of access are provided free. Additional hours are $2.00 per hour. Package B: For $14.95 per month, 20 hours of access are provided free. Additional hours are $1.00 per hour. Package C: For $19.95 per month unlimited access is provided. Write a program that calculates a customer's monthly bill. Note: the number of hours used in a month cannot exceed 744. Using the switch statement

31 1.class ISP 2.{ 3.static double PACKAGE_A = 9.95; 4.static double PACKAGE_B = 14.95; 5.static double PACKAGE_C = 19.95; 6. 7.static int MAX_HOURS = 744; 8. 9.int hours; 10.char packageType; 11.double charges; 12.String message; 13. 14.ISP(int h, char p) 15.{ 16.hours = h; 17.packageType = p; 18.} 19.}

32 boolean isGreaterThanZero() { return hours > 0 ; } boolean exceed744() { return hours > MAX_HOURS; } String getPackage() { return message; } double getCharges() { return charges; }

33 void calculateCharges() { switch(packageType) { case 'a': case 'A': message = "Package A"; charges = PACKAGE_A ; if (hours > 10) charges = charges + (hours - 10) * 2; break; case 'b': case 'B': message = "Package B"; charges = PACKAGE_B ; if (hours > 20) charges = charges + (hours - 20) * 2; break; case 'c': case 'C': message = "Package C"; charges = PACKAGE_C ; break; default: message = "No such package"; charges = 0; break; }

34 class TestPackage { public static void main(String[] arg) { ISP i = new ISP(200, 'H'); if (i.isGreaterThanZero()) { if (i.exceed744()) System.out.println("The hours exceeds the allowable limit"); else { i.calculateCharges(); System.out.println("Your package is " + isp.getPackage() + "\nYour charge for this month is " + isp.getCharges()); } } else System.out.println("Error: cannot calculate charges"); }


Download ppt "Control Structures Introduction Decision Statements The if Construct The if.. else Construct The switch Statement Iterative Constructs The while Construct."

Similar presentations


Ads by Google