Presentation is loading. Please wait.

Presentation is loading. Please wait.

5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus.

Similar presentations


Presentation on theme: "5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus."— Presentation transcript:

1 5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus

2 Topics The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements Decisions and Graphics More Components

3 Program Control Structures The program executes each statement one after another, unless otherwise directed explicitly. The program executes each statement one after another, unless otherwise directed explicitly. Order of execution statement is called “flow of control.” Order of execution statement is called “flow of control.” A program needs only three control structures: A program needs only three control structures: Sequence (default) Sequence (default) Conditional (decision) Conditional (decision) Iteration (loop) Iteration (loop)

4 Conditional Statements Conditional statement lets you choose which statement to execute next, depending of a boolean condition. Conditional statement lets you choose which statement to execute next, depending of a boolean condition. Conditional Statements Conditional Statements if statement if statement if-else statement if-else statement switch statement switch statement

5 If Statement if (boolCondition) someStatement; if (boolCondition) someStatement; if (boolCondition) { someStatement1; someStatement2; } if (boolCondition) { someStatement1; someStatement2; } bool Condition someStatement true false

6 If Statement final int VOTE_AGE = 18; int age; Scanner scan = new Scanner(System.in); System.out.println(“How old are you?”); age = scan.nextInt(); If (age >= VOTE_AGE) { System.out.println(“Since you are over “ + VOTE_AGE + “,\nyou can vote.”); }

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

8 Logical Operators If (5 > 3 && 8 3 && 8 <= 8) System.out.println(“Hi.”); Is (5 > 3 && 8 3 && 8 <= 8) true, or false? Logical operators take boolean expressions Logical operators take boolean expressions ! Logical NOT ! Logical NOT && Logical AND && Logical AND || Logical OR || Logical OR

9 Logical Operators int num; Scanner scan = new Scanner(System.in); System.out.println(“Enter a 2-digit number“); num = scan.nextInt(); if ((num >= 10) && (num < 100)) { System.out.println(“Thnak you.”); }

10 Your Turn Given: int a = 1; int b = 2; int c = 3; int d = 4; Given: int a = 1; int b = 2; int c = 3; int d = 4; True or False? True or False? 1.a d 2.a d 3.a a + b 4.!(c < d)

11 Truth Table AB!A A && B A || B TTFTT TFFFT FTTFT FFTFF

12 Boolean Expressions a > b found!found a > b && !found TT?? TF?? FT?? FF??

13 Short-circuited Operator If ((a > b) && (c b) && (c < d)) If (a > b) is false, then the whole espression is false. Thus, Java does not evaluate (c b) is false, then the whole espression is false. Thus, Java does not evaluate (c < d). If ((a > b) || (c b) || (c < d)) If (a > b) is true, then the whole expressions is true. Thus, Java does not evaluate (c b) is true, then the whole expressions is true. Thus, Java does not evaluate (c < d).

14 Topics The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements Decisions and Graphics More Components

15 If-Else Statement if (boolCondition) someStatement; else anotherStatement; if (boolCondition) someStatement; else anotherStatement; if (boolCondition) { someStatement1; someStatement2; } else { anotherStatement1; anotherStatement2; } if (boolCondition) { someStatement1; someStatement2; } else { anotherStatement1; anotherStatement2; } condition evaluated statement1 true false statement2

16 if –else Statements if (number > 0) System.out.println(number + " is positive.”); else System.out.println(number + " is non-pos.”); if (score >= 70) { grade = "Pass"; System.out.println("You passed the test."); } else { grade = "Fail"; System.out.println("You did not pass “ + “the test.”); }

17 Example Program CoinFlip.java CoinFlip.java CoinFlip.java Coin.java Coin.java Coin.java

18 Unmatched Else What is the output from the following example? What is the output from the following example? x = 5; if (x 0) System.out.print("Hi"); else System.out.print("Ho");

19 Answer Output: none Output: none An else is matched with the nearest if. An else is matched with the nearest if. Same as: Same as: x = 5; if (x 0) System.out.print("Hi"); else System.out.print("Ho");

20 Q & A Q: How do you associate a nested else with a particular if? Q: How do you associate a nested else with a particular if? A: A: x = 5; if (x 0) System.out.print("Hi"); } else { System.out.print("Ho"); }

21 Nested if Statement char grade; int score; 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’;

22 Nested If >= 90 score  input >= 80 >= 70 >= 60 grade = ‘A Grade = ‘F’ grade = ‘B’ grade = ‘C’ Grade = ‘D’ T T F F F F T T T

23 Equivalent if-else-if char grade; int score; 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’;

24 If-else-if >= 90 score  input >= 80 >= 70 >= 60 grade = ‘A Grade = ‘F’ grade = ‘B’ grade = ‘C’ Grade = ‘D’ T T F F F T T T F

25 Exercises Write a code segment which converts a letter grade into an equivalent numeric grade. I.e., A  4, B  3, C  2, D  1, F  0. Write a code segment which converts a letter grade into an equivalent numeric grade. I.e., A  4, B  3, C  2, D  1, F  0.

26 switch Statement Use switch statement when: Use switch statement when: Test condition involves matching with several cases Test condition involves matching with several cases Each value matched is an integer value—i.e., byte, short, int, or char (not String) Each value matched is an integer value—i.e., byte, short, int, or char (not String) Note that the switch statement cannot be used to convert a range of numeric scores to letter grades, e.g., 90-100  A, 80-89  B, etc. Why? Note that the switch statement cannot be used to convert a range of numeric scores to letter grades, e.g., 90-100  A, 80-89  B, etc. Why?

27 switch Statement: Example char grade; int score; … switch (grade){ case 'A': score = 4; break; case 'B': score = 3; break; case 'C': score = 2; break; case 'D': score = 1; break; default: score = 0; }

28 Your Turn Use a switch statement to count the number of vowels in a statement. Use a switch statement to count the number of vowels in a statement.

29 Solution String state  input String state  input int a = 0; e = 0; I = 0; o = 0; u = 0 int a = 0; e = 0; I = 0; o = 0; u = 0 for (int I = 0; I < state.lenght(); i++) ch + state.chartAt(i) for (int I = 0; I < state.lenght(); i++) ch + state.chartAt(i) switch(ch) case ‘a’: a++; break; case ‘e’: e++; break; case ‘I’: i++; break; case ‘o’; o++; break; case ‘u’; u++; switch(ch) case ‘a’: a++; break; case ‘e’: e++; break; case ‘I’: i++; break; case ‘o’; o++; break; case ‘u’; u++;

30 Topics The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements Decisions and Graphics More Components

31 Comparing Floating Point Numbers Given: int a, b; float x, y; Given: int a, b; float x, y; (a == b) is clear; but (a == b) is clear; but (x == y) should be avoided (x == y) should be avoided The expression may never be true. The expression may never be true. Two floating point numbers are equal only if they have the exact representation Two floating point numbers are equal only if they have the exact representation E.g., 0.3000000 is represented as 0.2999999. E.g., 0.3000000 is represented as 0.2999999.

32 Comparing Floating Point Numbers (cont.) Instead, use the following expression. final float DELTA = 0.00001; float x, y; … if (abs(a – b) <= DELTA) System.out.println(“close enough.”); Instead, use the following expression. final float DELTA = 0.00001; float x, y; … if (abs(a – b) <= DELTA) System.out.println(“close enough.”);

33 Comparing Characteres Comparison of characters Comparison of characters Based on Unicode numbers Based on Unicode numbers Called lexicographic order Called lexicographic order Note that numeric digit and alphabetic characters have consecutive Unicode numbers. Note that numeric digit and alphabetic characters have consecutive Unicode numbers. Characters Unicode Values 0 – 9 48 through 57 A – Z 65 through 90 a – z 97 through 122

34 Comparing Strings Given: String s1, s2; s1 = new String(“Abe”); s2 = new String(“Abe”); Given: String s1, s2; s1 = new String(“Abe”); s2 = new String(“Abe”); (s1 == s2) will return false, because s1 and s2 are essentially memory addresses. (s1 == s2) will return false, because s1 and s2 are essentially memory addresses. Generally speaking, do not use relational operators to compare objects. Generally speaking, do not use relational operators to compare objects.

35 Comparing Strings (cont.) Instead, use String mentods: Instead, use String mentods: If(s1.equals(s2)) System.out.println(“s1 == s2”); If(s1.equals(s2)) System.out.println(“s1 == s2”); n = s1.compareWith(s2); n = s1.compareWith(s2); If n is 0, then s1 == s2 If n is -1, then s1 < s2 If n = 1, then s1 > s2

36 Comparing Strings (cont.) The following expressions are all true. The following expressions are all true. “BOOK” < “book” “BOOK” < “book” “Venice” < “rome” “Venice” < “rome” “America” < “acupuncture” “America” < “acupuncture” “Santa Clara” < “Santa barbara” “Santa Clara” < “Santa barbara” “class” < “classical” “class” < “classical”

37 Topics The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements Decisions and Graphics More Components

38 While Statement While (boolean condition) { statement1 statement2 statement3 } While (boolean condition) { statement1 statement2 statement3 } One of the statements in the loop must cause a change in the value of the boolean condition. One of the statements in the loop must cause a change in the value of the boolean condition. statements true false condition evaluated

39 While Statement (cont.) cnt = 1; while (cnt <=10) { sum += cnt; cnt++; } cnt = 1; while (cnt <=10) { sum += cnt; cnt++; } While Statement Requirements: While Statement Requirements: 1. Loop control variable (LCV) is initialized 2. LCV is checked in the condition expression 3. LCV is updated in the loop  Average.java Average.java  WinPercentage.java WinPercentage.java

40 while Loop: Example Suppose that you save money each day, starting with 1 penny on day one, 2 pennies on day two, 4 pennies on day three, 8 pennies on day four, etc., each day doubling the amount from the preceding day. Write a program that calculates the number of days it takes to save at least $1,000,000. Suppose that you save money each day, starting with 1 penny on day one, 2 pennies on day two, 4 pennies on day three, 8 pennies on day four, etc., each day doubling the amount from the preceding day. Write a program that calculates the number of days it takes to save at least $1,000,000.

41 class WhileTest{ public static void main(String args[]){ int day; long total = 0; long save; long goal = 100000000; day = 0; save = 1; while (total < goal){ day++; total = total + save; save = 2 * save; } System.out.println("It takes " + day + " days to save at least $1,000,000."); } }

42 Nested Loops How many times will the string "Here" be printed? How many times will the string "Here" be printed? count1 = 1; while (count1 <= 5) { count2 = 1; while (count2 <= 3) { System.out.println ("Here"); count2++; } count1++; }

43 Sentinel Value Read and print sum of numbers input. Stop input when -1 is read. int sum = 0; int num; num = scan.nextInt(); while (num != -1) { sum += num; num = scan.nextInt(); } System.out.println(“Sum: “ + sum); Read and print sum of numbers input. Stop input when -1 is read. int sum = 0; int num; num = scan.nextInt(); while (num != -1) { sum += num; num = scan.nextInt(); } System.out.println(“Sum: “ + sum);

44 Sentinel Value (Cont.) Read and print the average of numbers input. Stop input when -1 is read. int sum = 0; int count = 0; int num; double ave; num = scan.nextInt(); while (num != -1) { count++; sum += num; num = scan.nextInt(); } System.out.println(“Ave: “ + (double)sum / count); Read and print the average of numbers input. Stop input when -1 is read. int sum = 0; int count = 0; int num; double ave; num = scan.nextInt(); while (num != -1) { count++; sum += num; num = scan.nextInt(); } System.out.println(“Ave: “ + (double)sum / count);

45 Topics The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements Decisions and Graphics More Components

46 For-Loop While-loop sum = 0; cnt = 1; while (cnt <= 10) { sum += cnt; cnt++; } While-loop sum = 0; cnt = 1; while (cnt <= 10) { sum += cnt; cnt++; } For-loop sum = 0; for (int cnt = 1; cnt <= 0; cnt++) { sum += 0; } For-loop sum = 0; for (int cnt = 1; cnt <= 0; cnt++) { sum += 0; }

47 Example Programs Multiples.java Multiples.java Multiples.java Stars.java Stars.java Stars.java

48 For-Loop int[] aList = {2, 4, 6, 8, 10}; for (int i = 0; i < aList.length; i++) System.out.println(aList[i] + “ ”); int sum = 0; for (int i = 0; i < aList.length; i++) sum = sum + aList[i]; System.out.println(“Sum: “ + sum);

49 Triangle Patterns Q: Write a program to produce the following patterns (one after another). Q: Write a program to produce the following patterns (one after another). * ** *** **** ***** ****** ******* ******** ********* ********** Answer: Answer: Answer:

50 class ArrayTest { String[] names = {"Mike", "Mary", "Martha"}; String[] addresses = new String[names.length]; void printList(){ for (int i = 0; i < names.length; i++) System.out.println(names[i] + " lives at " + addresses[i]); } public static void main(String args[]){ ArrayTest aList = new ArrayTest(); aList.addresses[0] = "123 Apple St."; aList.addresses[1] = "234 Banana Blvd."; aList.addresses[2] = "345 Citrus Ct."; aList.printList(); } }

51 Do-Loop do { statement1; statement2; } while (boolean condition) do { statement1; statement2; } while (boolean condition) Boolean condition is checked at the bottom of the loop. Boolean condition is checked at the bottom of the loop. A Do-Loop executes at least once, but While-Loop executes 0 or more times. A Do-Loop executes at least once, but While-Loop executes 0 or more times.

52 Comparing Do-Loop with While-Loop statement true false condition evaluated The while Loop true condition evaluated statement false The do Loop

53 Topics The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements Decisions and Graphics More Components


Download ppt "5. Conditionals & Loops Based on Java Software Development, 5 th Ed. By Lewis &Loftus."

Similar presentations


Ads by Google