1 / 62

5. Conditionals & Loops

5. Conditionals & Loops. Based on Java Software Development, 5 th Ed. By Lewis &Loftus. Topics. The if Statement and Conditions Other Conditional Statements Comparing Data The while Statement Iterators Other Repetition Statements Decisions and Graphics More Components.

gil-kim
Télécharger la présentation

5. Conditionals & 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. 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. 5. Conditionals & Loops Based on Java Software Development, 5th 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. • Order of execution statement is called “flow of control.” • A program needs only three control structures: • Sequence (default) • Conditional (decision) • Iteration (loop)

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

  5. boolCondition true false someStatement If Statement • if (boolCondition) someStatement; • if (boolCondition){ someStatement1; someStatement2;}

  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: • == 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 (=)

  8. Logical Operators • If (5 > 3 && 8 <= 8) System.out.println(“Hi.”); • Is (5 > 3 && 8 <= 8) true, or false? • Logical operators take boolean expressions • ! Logical NOT • && Logical AND • || 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; • True or False? • a < b && c > d • a < b || c > d • a < b && d > a + b • !(c < d)

  11. Truth Table

  12. Boolean Expressions

  13. Short-circuited Operator • If ((a > b) && (c < d)) • If (a > b) is false, then the whole espression is false. Thus, Java does not evaluate (c < d). • If ((a > b) || (c < d)) • If (a > 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. condition evaluated true false statement1 statement2 If-Else Statement • if (boolCondition) someStatement;else anotherStatement; • if (boolCondition){ someStatement1; someStatement2;}else{ anotherStatement1; anotherStatement2;}

  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 • Coin.java

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

  19. Answer • Output: none • An else is matched with the nearest if. • Same as: x = 5; if (x < 4) 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? • A: x = 5; if (x < 4){ 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 score input T F T >= 90 grade = ‘A T F >= 80 grade = ‘B’ T F >= 70 grade = ‘C’ F T >= 60 Grade = ‘F’ Grade = ‘D’

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

  24. If-else-if score input T T >= 90 grade = ‘A F T >= 80 grade = ‘B’ F T >= 70 grade = ‘C’ F T >= 60 Grade = ‘D’ F Grade = ‘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.

  26. Use switch statement when: Test condition involves matching with several cases 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? switch Statement

  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.

  29. Solution • String state  input • int a = 0; e = 0; I = 0; o = 0; u = 0 • 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++;

  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; • (a == b) is clear; but • (x == y) should be avoided • The expression may never be true. • Two floating point numbers are equal only if they have the exact representation • 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.”);

  33. Comparing Characteres • Comparison of characters • Based on Unicode numbers • Called lexicographic order • Note that numeric digit and alphabetic characters have consecutive Unicode numbers.

  34. Comparing Strings • 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. • Generally speaking, do not use relational operators to compare objects.

  35. Comparing Strings (cont.) • Instead, use String mentods: • If(s1.equals(s2)) System.out.println(“s1 == 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. • “BOOK” < “book” • “Venice” < “rome” • “America” < “acupuncture” • “Santa Clara” < “Santa barbara” • “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. condition evaluated true false statements While Statement • While (boolean condition){ statement1 statement2 statement3} • One of the statements in the loop must cause a change in the value of the boolean condition.

  39. While Statement (cont.) • cnt = 1;while (cnt <=10){ sum += cnt; cnt++;} • While Statement Requirements: • Loop control variable (LCV) is initialized • LCV is checked in the condition expression • LCV is updated in the loop • Average.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. 

  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? • 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);

  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);

  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-loopsum = 0;cnt = 1;while (cnt <= 10){ sum += cnt; cnt++;} • For-loopsum = 0;for (int cnt = 1; cnt <= 0; cnt++){ sum += 0;}

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

  48. For Loop (Your Turn) • Write an algorithm to solve each problem • Read a year value and check if it is a leap year. Do this for 10 inputs • In the preceding problem, let the user determine how many times to repeat • Let the user enter the first year and last year values, and count the number of leap years between the two years.

  49. Solution 1 loop (for n = 1 to 10) year  input put year if (year is a leap year) then put “ is a leap year” else put “ is NOT a leap year” end ifend loop

  50. Solution 2 last  inputloop (for n = 1 to last) year  input put year if (year is a leap year) then put “ is a leap year” else put “ is NOT a leap year” end ifend loop

More Related