Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing.

Similar presentations


Presentation on theme: "Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing."— Presentation transcript:

1 Chapter 5: Conditionals and loops

2 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

3 Outline Altering flow of control Boolean expressions Conditional Statements The while Statement Other Repetition Statements

4 Normal flow of control Flow of control The order in which statements are executed Execution normally proceeds in a linear fashion JAVA application begins with the first line of the main method And proceeds step by step to the end of the main method Some programming statements allow us to decide or not to execute a particular statement execute a statement over and over, repetitively

5 Conditional statements A conditional statement lets us choose which statement will be executed next is called sometimes selection statement The Java conditional statement are the if statement if-else statement switch statement

6 The if statement: syntax The if statement has the following syntax Example if (count > 20) System.out.println(“count exceeded”); if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed. If it is false, the statement is skipped.

7 Altering the flow of control: loop Loops allow to execute programs over and over again based on a boolean expression That determines how many times the statement is executed include while, do, and for statements Each type has unique characteristics

8 Conditional expressions All conditionals and loops are based on conditional expressions called Boolean expressions Use  Equality operators  Relational operators  Logical operators

9 Outline Altering flow of control Boolean expressions Conditional Statements The while Statement Other Repetition Statements

10 Equality operators The == and != are called equality operators == tests whether two values are equal != tests whether two values are not equal If (total != sum) System.out.println(“total does not equal sum”);

11 Relational operators They let us decide relative ordering between values Less than (<) Greater than (>) Less than or equal (<=) Greater than or equal (>=) Arithmetic operations have higher precedence

12 Logical operators Java has three logical operators They all take Boolean operands And produce Boolean results Logical NOT is unary operator Logical AND and OR are binary operators ! Logical NOT && Logical AND || Logical OR

13 Logical operators (cont’d) logical operator DescriptionExampleResult !Logical Not! aTrue if a is false and False if a is true &&Logical ANDa && bTrue if a and b are both true and false otherwise ||Logical ORa || bTrue if a or b are true and false otherwise

14 Logical operators: truth table A truth table Shows all possible true-false combinations of terms Since && and || each have 2 operands There are four possible combinations of conditions a and b aba && ba || b true false true falsetruefalsetrue false

15 Boolean expressions Consider the example if (total < MAX && !found) System.out.println(“Completed!.”); Under what condition would the println executed? total < MAX found!found total < MAX && !found false truefalse truefalse truefalsetrue false

16 Outline Altering flow of control Boolean expressions Conditional Statements The while Statement Other Repetition Statements

17 The if Statement If statement consists of The reserved word if followed by a Boolean expression enclosed in parentheses followed by a statement If (total > amount) total = total + amount; See Age.java Condition evaluated true statement false

18 The if-else statement Sometimes, we want to do one thing if a condition is true, and another thing if not We can add an else to an if to handle this situation if (height <= MAX) adjustment = 0; else adjustment = MAX – height; See Wages.java

19 The if Statement If statement consists of The reserved word if followed by a Boolean expression enclosed in parentheses followed by a statement If (total > amount) total = total + amount; See Age.java Condition evaluated true statement false

20 The if-else statement Sometimes, we want to do one thing if a condition is true, and another thing if not We can add an else to an if to handle this situation if (height <= MAX) adjustment = 0; else adjustment = MAX – height; See Wages.java

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

22 Using block statements To do more than one thing as a result Of boolean condition evaluation Replace any single statement with a block of statement A block of statement is a collection of statements enclosed in braces 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); }

23 Block statements In an if-else statement The if portion, or the else or both Could be block statements if (total > MAX) { System.out.println ("Error!!"); errorCount++; } else { System.out.println ("Total: " + total); current = total*2; }

24 Conditional operator Its syntax is 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 condition ? expression1 : expression2

25 Conditional operator (cont’d) Conditional operator is similar to an if-else statement is a ternary operator requiring three operands uses the symbol ? :, which are always separated ((total >MAX) ? total+1 : total * 2 total = ((total >MAX) ? total+1 : total * 2

26 Conditional operator (cont’d) total = (total > MAX) ? total+1 : total * 2 is equivalent to if (total > Max) total = total + 1 else total = total * 2

27 27 The Conditional Operator: Example 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

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

29 Nested if statements The statement executed as a result of if Could be another if statement This is called a nested if if (code == ‘R’) if (height <= 20) System.out.println(“Situation Normal”); else System.out.println (“Bravo”); is the else matched to the inner if statement or the outer if statement?

30 Nested if statements (cont’d) else clause is matched to the closest unmatched if that preceded it in the previous example, else is matched to if(height<=20) To avoid confusion, braces can be used to specify if statement to which an else belongs if (code == ‘R’) { if (height <= 20) System.out.println (“Situation Normal”); } else System.out.println (“Bravo”);

31 MinOfThree.Java import java.util.Scanner; public class MinOfThree { public static void main(String [] args) { 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) if (num1 < num3) min = num1; else min = num3; else if (num2<num3) min = num2; else min = num3; System.out.println(“Minimum value: “+ min); }

32 Comparing data

33 Comparing Data When comparing data using boolean expressions understand the nuances of certain data types Let's examine some key situations: Comparing floating point values for equality Comparing characters Comparing strings (alphabetical order) Comparing object vs. comparing object references

34 Comparing Float Values You should rarely use the equality operator ( == ) when comparing two floating point values Two floating point values are equal if the underlying binary representations match exactly Computations often result in slight differences that may be irrelevant In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly equal

35 Comparing Float Values To determine the equality of two floats, you may want to use the following technique: if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal"); If the difference between two floating point values is less than the tolerance, they are considered to be equal The tolerance could be set to any appropriate level, such as 0.000001

36 Comparing Characters Java character data is based on the Unicode character set Unicode establishes a particular numeric value for each character, and therefore an ordering We can use relational operators on character data based on this ordering For example, the character '+' is less than the character ' J' because it comes before it in the Unicode character set

37 Comparing Characters In Unicode, the digit characters (0-9) are contiguous and in order the uppercase letters (A-Z) & lowercase letters (a-z) are contiguous and in order CharactersUnicode Values 0 – 948 through 57 A – Z65 through 90 a – z97 through 122

38 Comparing Strings Remember that in Java a character string is an object The equals method can be called with strings to determine if two strings contain the same characters in the same order The equals method returns a boolean result if (name1.equals(name2)) System.out.println ("Same name");

39 Comparing Strings We cannot use the relational operators to compare strings The String class contains a method called compareTo to determine if one string comes before another

40 Comparing Strings A call to name1.compareTo(name2) returns zero if name1 and name2 are equal (contain the same characters) returns a negative value if name1 is less than name2 returns a positive value if name1 is greater than name2

41 Comparing Strings if (name1.compareTo(name2) < 0) System.out.println (name1 + "comes first"); else if (name1.compareTo(name2) == 0) System.out.println ("Same name"); else System.out.println (name2 + "comes first"); Because comparing characters and strings is based on a character set, it is called a lexicographic ordering

42 Lexicographic Ordering Lexicographic ordering is not strictly alphabetical when uppercase and lowercase characters are mixed For example, the string "Great" comes before the string "fantastic" because all of the uppercase letters  come before all of the lowercase letters in Unicode Also, short strings come before longer strings with the same prefix (lexicographically) Therefore "book" comes before "bookcase"

43 Comparing Objects The == operator can be applied to objects it returns true if the two references are aliases of each other The equals method is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator It has been redefined in the String class to compare the characters in the two strings

44 The switch statement Provides another way to decide which statement To execute next Evaluates an expression that attempts to match The result of one of several possible cases Each case contains a value and a list of statements The flow of control transfer to the statement  Associated with the first case value that matches

45 Switch statement: syntax The general syntax of switch statement is switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case... } switch and case are reserved words If expression matches value2, control jumps to here

46 The switch Statement Often a break statement is used as last statement in each case's statement list A break statement Transfers control to end of the switch statement If a break statement is not used, flow of control will continue to the next case Sometimes this may be appropriate, but often we want to execute only statements associated with one case

47 The switch Statement switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; } An example of a switch statement:

48 The switch Statement A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches

49 Switch example switch(idchar) { case ‘A’: acount = acount+1; break; case ‘B’: bcount=bcount+1; break; default: System.out.println(“Error identifying Character”); } Type of expression evaluated by switch Char, byte, short, or int

50 Use of a switch statement Sample program A comment is printed according to a user’s grade Grade = 100 => a perfect score; Grade = 90s (Excellent)..etc Algorithm Ask user to enter a grade Based on grade value, print the right comment See GradeReport.java

51 Outline Altering flow of control Boolean expressions Conditional Statements The while Statement Other Repetition Statements


Download ppt "Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing."

Similar presentations


Ads by Google