 Download Presentation Conditionals and Loops

# Conditionals and Loops - PowerPoint PPT Presentation

5. Conditionals and Loops. Conditionals and Loops. Now we will examine programming statements that allow us to: make decisions repeat processing steps in a loop Chapter 5 focuses on: boolean expressions conditional statements comparing data repetition statements iterators I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.
Download Presentation ## Conditionals and Loops

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript
1. 5 Conditionals and Loops

2. Conditionals and Loops • Now we will examine programming statements that allow us to: • make decisions • repeat processing steps in a loop • Chapter 5 focuses on: • boolean expressions • conditional statements • comparing data • repetition statements • iterators • more drawing techniques • more GUI components (skip)

3. Outline The if Statement and Conditions – Oct. 25 Other Conditional Statements – Oct. 25 Comparing Data – Oct. 30 The while Statement – Nov. 8 Iterators – Nov. 8 Other Repetition Statements – Nov. 8, 13 Decisions and Graphics – Nov. 13 More Components (skip)

4. Flow of Control • Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence • Some programming statements allow us to: • decide whether or not to execute a particular statement • execute a statement over and over, repetitively • These decisions are controlled by boolean expressions (or conditions) that evaluate to true or false • The order of statement execution is called the flow of control

5. Conditional Statements • A conditional statement lets us choose which statement will be executed next • Therefore they are sometimes called selection statements • Conditional statements give us the power to make basic decisions • The Java conditional statements are the: • if statement • if-else statement • switch statement

6. Examples of if statements Double hoursWorked; // Scan in a value of hoursWorked. if (hoursWorked > 40.0 ) grossPay = 40 * payRate + 1.5 * payRate * (hoursWorked – 40); int heightInInches; // Scan in a value of heightInInches if (heightInInches < 48 ) system.out.println(“Customer too small,” + “ do not let on ride.”);

7. The condition must be a boolean expression. It must evaluate to either true or false. ifis a Java reserved word If the condition is true, the statement is executed. If it is false, the statement is skipped. The if Statement • The if statement has the following syntax: if ( condition ) statement;

8. condition evaluated true false statement Logic of an if statement

9. Boolean Expressions • A condition often uses one of Java's equality operators or relational operators, which all return boolean results: ==equal to !=not equal to <less than >greater than <=less than or equal to >=greater than or equal to • Note the difference between the equality operator (==) and the assignment operator (=)

10. The if Statement • An example of an if statement: if (sum > MAX) delta = sum - MAX; System.out.println ("The sum is " + sum); • First the condition is evaluated -- the value of sum is either greater than the value of MAX, or it is not • If the condition is true, the assignment statement is executed -- if it isn’t, it is skipped. • Either way, the call to println is executed next • See Age.java (page 216)

11. Age.java (page 216) import java.util.Scanner;public class Age{ // Reads the user's age and prints comments accordingly. public static void main (String[] args) { final int MINOR = 21; Scanner scan = new Scanner (System.in); System.out.print ("Enter your age: "); int age = scan.nextInt(); System.out.println ("You entered: " + age); if (age < MINOR) System.out.println ("Youth is a wonderful thing. Enjoy."); System.out.println ("Age is a state of mind."); } }

12. Age.java (page 216) output • Enter your age: 19You entered: 19Youth is a wonderful thing. Enjoy.Age is a state of mind. • Enter your age: 57You entered: 57Age is a state of mind.

13. Indentation • The statement controlled by the if statement is indented to indicate that relationship • The use of a consistent indentation style makes a program easier to read and understand • Although it makes no difference to the compiler, proper indentation is crucial to understanding the flow of the program. "Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live." -- Martin Golding

14. The if Statement • What do the following statements do? if (top >= MAXIMUM) top = 0; Sets top to zero if the current value of top is greater than or equal to the value of MAXIMUM if (total != stock + warehouse) inventoryError = true; Sets a flag to true if the value of total is not equal to the sum of stock and warehouse • The precedence of the arithmetic operators is higher than the precedence of the equality and relational operators

15. Logical Operators • Boolean expressions can also use the following logical operators: !Logical NOT &&Logical AND ||Logical OR • They all take boolean operands and produce boolean results • Logical NOT is a unary operator (it operates on one operand) • Logical AND and logical OR are binary operators (each operates on two operands)

16. Logical NOT • The logical NOT operation is also called logical negation or logical complement • If some boolean condition a is true, then !a is false; if a is false, then !a is true • Logical expressions can be shown using a truth table

17. Logical AND and Logical OR • The logical AND expression a && b is true if both a and b are true, and false otherwise • The logical OR expression a || b is true if either a or b or both are true, and false otherwise

18. Logical Operators • Expressions that use logical operators can form complex conditions if (total < MAX+5 && !found) System.out.println ("Processing…"); • All logical operators have lower precedence than the relational operators • Logical NOT has higher precedence than logical AND and logical OR

19. Logical Operators • A truth table shows all possible true-false combinations of the terms • Since && and || each have two operands, there are four possible combinations of conditions a and b

20. Boolean Expressions • Specific expressions can be evaluated using truth tables

21. Short-Circuited Operators • The processing of logical AND and logical OR is “short-circuited” • If the left operand is sufficient to determine the result, the right operand is not evaluated if (count != 0 && total/count > MAX) System.out.println ("Testing…"); • This type of processing must be used carefully • Usually short circuiting has no effect on your code and can be ignored.

22. Outline The if Statement and Conditions – Oct. 25 Other Conditional Statements – Oct. 25 Comparing Data – Oct. 30 The while Statement – Nov. 8 Iterators – Nov. 8 Other Repetition Statements – Nov. 8, 13 Decisions and Graphics – Nov. 13 More Components (skip)

23. The if-else Statement • An else clause can be added to an if statement to make an if-else statement if ( condition ) statement1; else statement2; • If the condition is true, statement1 is executed; if the condition is false, statement2 is executed • One or the other will be executed, but not both • See Wages.java (page 219)

24. public class Wages{ // Reads the number of hours worked and calculates wages. public static void main (String[] args) { final double RATE = 8.25; // regular pay rate final int STANDARD = 40; // standard hours in a work week Scanner scan = new Scanner (System.in); double pay = 0.0; System.out.print ("Enter the number of hours worked: "); int hours = scan.nextInt(); System.out.println (); // Pay overtime at "time and a half" if (hours > STANDARD) pay = STANDARD * RATE + (hours-STANDARD) * (RATE * 1.5); else pay = hours * RATE; NumberFormat fmt = NumberFormat.getCurrencyInstance(); System.out.println ("Gross earnings: " + fmt.format(pay)); } }

25. Wages.java (page 219) output • Enter the number of hours worked: 40Gross earnings: \$330.00 • Enter the number of hours worked: 50Gross earnings: \$453.75

26. condition evaluated true false statement1 statement2 Logic of an if-else statement

27. The Coin Class • Let's examine a class that represents a coin that can be flipped • Instance data is used to indicate which face (heads or tails) is currently showing • See CoinFlip.java (page 220) • See Coin.java (page 221)

28. // CoinFlip.java Author: Lewis/Loftus//// Demonstrates the use of an if-else statement.public class CoinFlip{ // Creates a Coin object, flips it, and prints the results. public static void main (String[] args) { Coin myCoin = new Coin(); myCoin.flip(); System.out.println (myCoin); if (myCoin.isHeads()) System.out.println ("You win."); else System.out.println ("Better luck next time."); }}

29. CoinFlip.java (page 220) output • TailsBetter luck next time. • HeadsYou win.

30. Coin API Constructor public Coin () Sets up the coin by flipping it initially Methods public void flip () - Flips the coin by randomly choosing a face value. . public boolean isHeads () - Returns true if the current face of the coin is heads. public String toString() - Returns the current face of the coin as a string, “Heads” or “Tails”

31. public class Coin { private final int HEADS = 0; private final int TAILS = 1; private int face; // Constructor Sets up the coin by flipping it initially. public Coin () { flip(); } // Flips the coin by randomly choosing a face value. public void flip () { face = (int) (Math.random() * 2); } // Returns true if the current face of the coin is heads. public boolean isHeads () { return (face == HEADS); } // Check this out // Returns the current face of the coin as a string. public String toString() // Can you reduce this by 1 stment? { String faceName; if (face == HEADS) faceName = "Heads"; else faceName = "Tails"; return faceName; }}

32. Indentation Revisited • Remember that indentation is for the human reader, and is ignored by the computer if (total > MAX) System.out.println ("Error!!"); errorCount++; Despite what is implied by the indentation, the increment will occur whether the condition is true or not

33. Block Statements • Several statements can be grouped together into a block statement delimited by braces • A block statement can be used wherever a statement is called for in the Java syntax rules if (total > MAX) { System.out.println ("Error!!"); errorCount++; }

34. Block Statements • In an if-else statement, the if portion, or the else portion, or both, could be block statements if (total > MAX) { System.out.println ("Error!!"); errorCount++; } else { System.out.println ("Total: “ + total); current = total*2; } • See Guessing.java (page 223)

35. public class Guessing{ // Plays a simple guessing game with the user. public static void main (String[] args) { final int MAX = 10; int answer, guess; Scanner scan = new Scanner (System.in); Random generator = new Random(); answer = generator.nextInt(MAX) + 1; System.out.print ("I'm thinking of a number between 1 and " + MAX + ". Guess what it is: "); guess = scan.nextInt(); if (guess == answer) System.out.println ("You got it! Good guessing!"); else { System.out.println ("That is not correct, sorry."); System.out.println ("The number was " + answer); } }}

36. Guessing.java (page 223) output • I'm thinking of a number between 1 and 10. Guess what it is: 7That is not correct, sorry.The number was 2 • I'm thinking of a number between 1 and 10. Guess what it is: 1You got it! Good guessing!

37. The Conditional Operator • Java has a conditional operator that uses a boolean condition to determine which of two expressions is evaluated • Its syntax is: condition ? expression1 : expression2 • If the condition is true, expression1 is evaluated; if it is false, expression2 is evaluated • The value of the entire conditional operator is the value of the selected expression

38. The Conditional Operator • The conditional operator is similar to an if-else statement, except that it is an expression that returns a value • For example: larger = ((num1 > num2) ? num1 : num2); • If num1 is greater than num2, then num1 is assigned to larger; otherwise, num2 is assigned to larger • The conditional operator is ternary because it requires three operands

39. Evaluate this expression Return this value if expression is true Return this value if expression is false The Conditional Operator int num1 = 5, num2 = 3; larger = ((num1 > num2) ? num1 : num2); What is the value of larger when this is done? Answer: 5

40. The Conditional Operator • Another example: System.out.println ("Your change is " + count +((count == 1) ? "Dime" : "Dimes")); • If count equals 1, then "Dime" is printed • If count is anything other than 1, then "Dimes" is printed

41. Nested if Statements • The statement executed as a result of an if statement or else clause could be another if statement • These are called nested if statements • See MinOfThree.java (page 227) • An else clause is matched to the last unmatched if (no matter what the indentation implies) • Braces can be used to specify the if statement to which an else clause belongs

42. MinOfThree.java (page 227) bad example int num1, num2, num3, min = 0; Scanner scan = new Scanner (System.in); System.out.println ("Enter three integers: "); num1 = scan.nextInt(); num2 = scan.nextInt(); num3 = scan.nextInt(); if (num1 < num2) // more confusing than it needs to be if (num1 < num3) min = num1; else min = num3; else if (num2 < num3) min = num2; else min = num3; System.out.println ("Minimum value: " + min);

43. MinOfThree.java (page 227) output • Enter three integers: 5 1 3Minimum value: 1 • Enter three integers: 1 3 5Minimum value: 1 • Enter three integers: 3 5 1 Minimum value: 1

44. MinOfThree.java (page 227) improved(but no longer demonstrates nested if else) int num1, num2, num3, min = 0; Scanner scan = new Scanner (System.in); System.out.println ("Enter three integers: "); num1 = scan.nextInt(); num2 = scan.nextInt(); num3 = scan.nextInt(); min = num1; if (num2 < min) min = num2; if (num3 < min) min = num3; System.out.println ("Minimum value: " + min);

45. Tax Rate Problem • Let’s say that there are 4 income tax rates in some country. • The rates are:0 <= income < 10,000: tax rate = 0% 10,000 <= income < 30,000: tax rate = 5% 30,000 <= income < 60,000: tax rate = 10% income >= 60,000: tax rate = 15% • Write a program that inputs a person’s income and prints out their maximum tax rate.

46. Tax Program design What do we need to do? Let’s set up some steps. • Ask the user to input their amount of income, can be dollars and cents. • Read the income • Based on income, figure out tax rate: A person making less than \$10,000 has 0% tax A person making \$10,000 but less than \$30,000 has 5% tax A person making \$30,000 but less than \$60,000 has 10% tax A person making more than \$60,000 has 15% tax. 4. Print out the maximum tax rate.

47. Tax rate program, first try, no if else double income, maxTax = 0.0;Scanner scan = new Scanner (System.in);System.out.print ("Enter the annual income: ");income = scan.nextDouble();if (income < 10000.0) // This test can be eliminated, why? maxTax = 0.0;if (income >= 10000.0 && income < 30000.0 ) maxTax = 0.05;if (income >= 30000.0 && income <60000.0 ) maxTax = 0.10;if (income >= 60000.0) maxTax = 0.15; System.out.println ("Maximum tax rate: " + NumberFormat.getPercentInstance().format(maxTax));

48. Tax rate program, cleaner version double income, maxTax = 0.0; Scanner scan = new Scanner (System.in);System.out.print ("Enter the annual income: ");income = scan.nextDouble();if (income < 10000) maxTax = 0.0; else if (income < 30000 ) maxTax = 0.05; else if (income < 60000 ) maxTax = 0.10; else maxTax = 0.15;System.out.println ("Maximum tax rate: " + NumberFormat.getPercentInstance().format(maxTax));

49. condition evaluated true false statement1 statement2 Logic of an if-else statement Statement2 consists of several if else’s but the entire thing is skipped if the condition is true.

50. The switch Statement • The switch statement provides another way to decide which statement to execute next • The switch statement evaluates an expression, then attempts to match the result to one of several possible cases • Each case contains a value and a list of statements • The flow of control transfers to statement associated with the first case value that matches