1 / 85

Chapter Topics

Chapter Topics. Chapter 3 discusses the following main topics: The if Statement The if - else Statement Nested if statements The if - else - if Statement Logical Operators Comparing String Objects. Chapter Topics. Chapter 3 discusses the following main topics:

jkindred
Télécharger la présentation

Chapter Topics

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. Chapter Topics Chapter 3 discusses the following main topics: The if Statement The if-else Statement Nested if statements The if-else-if Statement Logical Operators Comparing String Objects

  2. Chapter Topics Chapter 3 discusses the following main topics: More about Variable Declaration and Scope The Conditional Operator The switch Statement Displaying Formatted Output with System.out.printf and String.format

  3. The if Statement The if statement decides whether a section of code executes or not. The if statement uses a boolean to decide whether the next statement or block of statements executes. if (boolean expression is true) execute next statement.

  4. Flowcharts If statements can be modeled as a flow chart. Yes Is it cold outside? Wear a coat. boolean coldOutside = true; … if (coldOutside) wearCoat(); int xyz, abc; … if (xyz == abc) {incXYZ(); xyz++;} abc = xyz;

  5. Flowcharts A block if statement may be modeled as: Yes Is it cold outside? Wear a coat. Wear a hat. Wear gloves. boolean coldOutside = false; if (coldOutside){ wearCoat(); wearHat(); wearGloves(); } Note the use of curly braces to block several statements together.

  6. Relational Operators In most cases, the boolean expression, used by the if statement, uses relational operators.

  7. Boolean Expressions A boolean expressionis any variable or calculation that results in a true or falsecondition.

  8. if Statements and Boolean Expressions if (x > y) System.out.println("X is greater than Y" + boolean(x > y)); if(x == y) System.out.println("X is equal to Y"); if(x != y) { System.out.println("X is not equal to Y"); x = y; System.out.println("However, now it is."); } Example: AverageScore.java

  9. package booleanStudy; publicclass BooleanExpr { publicstaticvoid main(String[] args) { booleanrainingDay = false; intx = 100, y = 50; x = 20; y = 40; if (x > y) {System.out.println("rainingDay is " + rainingDay); System.out.println("x > y? is " + (boolean)(x>y));} elseif (x == y) { System.out.println("x > y? is " + (boolean)(x>y)); System.out.println("x = y? is " + (boolean)(x == y));} else { System.out.println("x > y? is " + (boolean)(x > y)); System.out.println("x = y? is " + (boolean)(x == y)); System.out.println("x < y? is " + (boolean)(x < y));} System.out.println("End of if ese if else!"); } } Do not need the (boolean) to cast (x > y) etc. Simply use (x > y) will yield true or false. Output: x > y? is false x = y? is false x < y? is true End of if ese if else!

  10. Programming Style and if Statements An if statement can span more than one line; however, it is still one statement. if (average > 95) grade = ′A′; is functionally equivalent to if(average > 95) grade = ′A′;

  11. Programming Style and if Statements Rules of thumb: The conditionally executed statement should be on the line after the if condition. The conditionally executed statement should be indented one level from the if condition. If an if statement does not have the block curly braces, it is ended by the first semicolon encountered after the if condition. if (expression) statement; No semicolon here.Semicolon ends statement here.

  12. Block if Statements Conditionally executed statements can be grouped into a block by using curly braces {} to enclose them. If curly braces are used to group conditionally executed statements, the if statement is ended by the closing curly brace. if (expression) { statement1; statement2; } Curly brace ends the statement.

  13. Block if Statements Remember that when the curly braces are not used, then only the next statement after the if condition will be executed conditionally. if (expression) statement1; statement2; statement3; Only this statement is conditionally executed.

  14. Flags A flag is a boolean variable that monitors some condition in a program. booleanhighScore; When a condition is true, the flag is set to true. The flag can be tested to see if the condition has changed. if (average > 95) highScore = true; Later, this condition can be tested: if (highScore) System.out.println("That′s a high" + "score!");

  15. Comparing Characters Characters can be tested with relational operators. Characters are stored in memory using the Unicode character format. Unicode is stored as a sixteen (16) bit number. Characters are ordinal, meaning they have an order in the Unicode character set. Since characters are ordinal, they can be compared to each other. char c = ′A′; if(c < ′Z′) System.out.println("A is less than Z");

  16. charc = 'A'; if(c < 'Z') System.out.println("A is less than Z is " + (boolean)(c < 'Z’)); System.out.println("A is less than Z is " + (c < 'Z')); Output is: A is less than Z is true A is less than Z is true

  17. if-else Statements The if-else statement adds the ability to conditionally execute code when the if condition is false. if (expression) statementOrBlockIfTrue; else statementOrBlockIfFalse; See example: Division.java

  18. if-else Statement Flowcharts Yes Is it cold outside? Wear shorts. Wear a coat. No if (Is it cold outside) wear_short; else wear_a_coat;

  19. Nested if Statements If an if statement appears inside another if statement (single or block) it is called a nested if statement. The nested if is executed only if the outer if statement results in a true condition. See example: LoanQualifier.java

  20. Nested if Statement Flowcharts No Yes Is it cold outside? Wear shorts. Is it snowing? Yes No Wear a jacket. Wear a parka.

  21. Nested if Statements Is it cold outside? No Yes Wear shorts. Is it snowing? Yes No Wear a jacket. Wear a parka. boolean coldOutside, snowing; coldOutside = true; snowing = false; if (coldOutside) { if (snowing) { wearParka(); } else { wearJacket(); } } else { wearShorts(); }

  22. if-else Matching Curly brace use is not required if there is only one statement to be conditionally executed. However, sometimes curly braces can help make the program more readable. Additionally, proper indentation makes it much easier to match up else statements with their corresponding if statement.

  23. Alignment and Nested if Statements if (coldOutside) { if (snowing) { wearParka(); } else { wearJacket(); } } else { wearShorts(); } This ifand else go together. This ifand else go together.

  24. Alignment and Nested if Statements if (coldOutside) { if (snowing) { wearParka(); } else { wearJacket(); } } else { wearShorts(); } This ifand else go together. This ifand else go together.

  25. if-else-if Statements if (expression_1) { statement; statement; etc. } else if (expression_2) { statement; statement; etc. } Insert as many else if clauses as necessary else { statement; statement; etc. } If expression_1 is true these statements are executed, and the rest of the structure is ignored. Otherwise, if expression_2 is true these statements are executed, and the rest of the structure is ignored. These statements are executed if none of the expressions above are true.

  26. if-else-if Statements • if (expression_1) • { • statement; • statement; • etc. • } • else • if (expression_2) • { • statement; • statement; • etc. • } • Insert as many else if clauses as necessary • else • { • statement; • statement; • etc. • } If expression_1 is true these statements are executed, and the rest of the structure is ignored. Otherwise, if expression_2 is true these statements are executed, and the rest of the structure is ignored. These statements are executed if none of the expressions above are true.

  27. if-else-if Statements Nested if statements can become very complex. The if-else-if statement makes certain types of nested decision logic simpler to write. Care must be used since else statements match up with the immediately preceding unmatched if statement. See example: TestResults.java

  28. if-else-if Flowchart

  29. package chapter03; • importjava.util.Scanner; • publicclass Chapter03Example { • publicstaticvoid main(String[] args) { • intscore; • chargrade; • Scanner kbInput = new Scanner(System.in); • System.out.println("Enter a score, integer only, such as 60: "); • score = kbInput.nextInt(); • if (score < 60) • { grade = 'F'; • System.out.println("Grade is " + grade); • } • elseif (score < 70) • { grade = 'd'; • System.out.println("Grade is " + grade); • } • elseif (score < 80) • { • grade = 'C'; • System.out.println("Grade is " + grade); • } • elseif (score < 90) • { • grade = 'B'; • System.out.println("Grade is " + grade); • } • elseif (score <= 100) • { • grade = 'B'; • System.out.println("Grade is " + grade); • } • else • { • grade = 'X'; • System.out.println("Grade is " + grade); • } • } • }

  30. Logical Operators Java provides two binary logical operators(&& and ||) that are used to combine boolean expressions. e.g. int x= 70, y = 60, z = 70; if (((x > y) || (y > x)) && (y = = z)) System.out.printf(“you %s”, “Good!”); Java also provides one unary (!) logical operator to reverse the truth of a boolean expression. if (((x > y) || (y > x)) && !(y = = z)) System.out.printf(“you %s”, “Good!”);

  31. Logical Operators

  32. The && Operator The logical AND operator (&&) takes two operands that must both be boolean expressions. The resulting combined expression is true if (and only if) both operands are true. See example: LogicalAnd.java

  33. The || Operator The logical OR operator (||) takes two operands that must both be boolean expressions. The resulting combined expression is false if (and only if) both operands are false. Example: LogicalOr.java

  34. The ! Operator The ! operator performs a logical NOT operation. If an expression is true, !expression will be false. if (!(temperature > 100)) System.out.println("Below the maximum" + " temperature."); If temperature > 100 evaluates to false, then the output statement will be run.

  35. Short Circuiting Logical AND and logical OR operations perform short-circuit evaluationof expressions. Logical AND will evaluate to false as soon as it sees that one of its operands is a false expression. Logical OR will evaluate to true as soon as it sees that one of its operands is a true expression.

  36. Order of Precedence The ! operator has a higher order of precedence than the && and || operators. The && and || operators have a lower precedence than relational operators like < and >. Parenthesis can be used to force the precedence to be changed.

  37. Order of Precedence

  38. Comparing String Objects In most cases, you cannot use the relational operators to compare two String objects. Reference variables contain the address of the object they represent. Unless the references point to the same object, the relational operators will not return true. See example: StringCompare.java See example: StringCompareTo.java

  39. Summary of the following next few slides: String one = "projects!"; String two = "projectiles!"; System.out.println(one.compareTo(two)); //10 = code(s) – code(i) System.out.println(two.compareTo(one)); //-10 = code(i) – code(s) String one = "project"; String two = "projectiles!"; System.out.println(one.compareTo(two)); //-5 – the string project Has 5 characters less than projectiles! System.out.println(two.compareTo(one)); //5 – the string projectiles! Has 5 characters more than project! String one = "project "; String two = "projectiles!"; System.out.println(one.compareTo(two)); //-73 = code(space) – code(i) System.out.println(two.compareTo(one)); //73 = code(i) – code(space)

  40. String one = "projects!"; String two = "projectiles!"; System.out.println("The codes for s and i: " + 's' + " is " + (int)('s') + " and " + 'i' + " is " + (int)('i')); System.out.printf("The codes for %c and %c are %d and % d.", 's', 'i', (int)('s'), (int)('i')); System.out.println("\n" + one.compareTo(two)); //10 = code(s) – code(i) = 115 - 105 System.out.println(two.compareTo(one)); //-10 = code(i) – code(s) = 105 - 115 Output is: The codes for s and i: s is 115 and i is 105 The codes for s and i are 115 and 105. 10 -10

  41. String one = "project"; String two = "projectiles!"; System.out.printf("Given two strings one has \"%s\" and two has \"%s\",\n" + "the operation of one.compareTo(two) " + "has the value : %d\n", "project", "projectiles!", one.compareTo(two)); System.out.println(one.compareTo(two) + " = " + one.length() + " - " + two.length()); //-5 – the string project Has 5 characters less than projectiles! System.out.println("The two.compareTo(one) is " + two.compareTo(one)); //5 – the string projectiles! Has 5 characters more than project! Output is : Given two strings one has "project" and two has "projectiles!", the operation of one.compareTo(two) has the value : -5 -5 = 7 - 12 The two.compareTo(one) is 5

  42. String one = "project "; String two = "projectiles!"; System.out.println("The codes for space and i: " + ' ' + " is " + (int)(' ') + " and " + 'i' + " is " + (int)('i')); System.out.printf("The codes for %c and %c are %d and %d.", ' ', 'i', (int)(' '), (int)('i')); System.out.println("\nThe one.compareTo(two) operation yields " + one.compareTo(two)); //-73 = code(space) – code(i) System.out.println("The two.compareTo(one) operation yields " + two.compareTo(one)); //73 = code(i) – code(space) Output is: The codes for space and i: is 32 and i is 105 The codes for and i are 32 and 105. The one.compareTo(two) operation yields -73 The two.compareTo(one) operation yields 73

  43. String oneStr = new String("tam"); String twoStr = new String("tam"); System.out.println(oneStr == twoStr); //false since they contain addresses booleanequalStrings = oneStr == twoStr; System.out.println(equalStrings); //false, since they contain addresses equalStrings = oneStr.equals(twoStr); System.out.println(equalStrings); //true, method equals on strings ("tam"); System.out.println(oneStr.equals(twoStr)); Conclusion: Each reference variable oneStr or twoStr reference their string objects which have the same string literal “tam”. Output is: false false true

  44. The Difference of the following statements: String str = new String(“1amb”); and String str = “lamb”; String oneStr = new String("tam"); String twoStr = new String("tam"); String oneStr1 = "tam"; String twoStr1 = "tam";

  45. String oneStr = new String("tam"); String twoStr = new String("tam"); System.out.println(oneStr == twoStr); //false since they contain addresses booleanequalStrings = oneStr == twoStr; System.out.println(equalStrings); //false, since they contain addresses equalStrings = oneStr.equals(twoStr); System.out.println(equalStrings); //true, method equals on strings ("tam"); System.out.println(oneStr.equals(twoStr));//true Output is: false false true true Conclusion: Each reference variable oneStr or twoStr reference their string objects which have the same string literal “tam”.

  46. String oneStr1 = "tam"; String twoStr1 = "tam"; System.out.println(oneStr1 == twoStr1); //true booleanequalStrings1 = oneStr1 == twoStr1; System.out.println(equalStrings1); //true equalStrings = oneStr1.equals(twoStr1); System.out.println(equalStrings1); //true System.out.println(oneStr1.equals(twoStr1)); //true Conclusion: Both reference variables, oneStr1 and twoStr1 references the same string object "tam ". true true True True

  47. Ignoring Case in String Comparisons In the String class the equals and compareTomethods are case sensitive. In order to compare two String objects that might have different case, use: equalsIgnoreCase, or compareToIgnoreCase See example: SecretWord.java

  48. System.out.println("The compareTo results " + "dope".compareTo("dome")); System.out.println("The compareTo results " + "doPe".compareTo("dome")); System.out.println("The compareToIgnoreCase results " + "DOPE".compareToIgnoreCase("dome")); The compareTo results 3 //obtained from code(p) – code(m) The compareTo results -29//code(P) = 80 – code(m) = 109 The compareToIgnoreCase results 3 //obtained from code(P) – code(M) or code(p) – code(m).

  49. Variable Scope In Java, a local variable does not have to be declared at the beginning of the method. The scope of a local variable begins at the point it is declared and terminates at the end of the method. When a program enters a section of code where a variable has scope, that variable has come into scope, which meansthe variable is visible to the program. See example: VariableScope.java

More Related