Your SlideShare is downloading. ×
0
Week 3ConditionalStatements
© 2004 Pearson Addison-Wesley. All rights reserved 5-2Copyright WarningCOMMONWEALTH OF AUSTRALIACopyright Regulations 1969...
© 2004 Pearson Addison-Wesley. All rights reserved 5-3Conditional Statements• Now we will examine programming statementsth...
© 2004 Pearson Addison-Wesley. All rights reserved 5-4OutlineThe if Statement and ConditionsOther Conditional StatementsCo...
© 2004 Pearson Addison-Wesley. All rights reserved 5-5Flow of Control• Unless specified otherwise, the order of statemente...
© 2004 Pearson Addison-Wesley. All rights reserved 5-6Conditional Statements• A conditional statement lets us choose which...
© 2004 Pearson Addison-Wesley. All rights reserved 5-7The IF Statement• Looks like the followingif ( condition ){statement...
© 2004 Pearson Addison-Wesley. All rights reserved 5-8The IF Statement• The else { … } section is optional If we dont nee...
© 2004 Pearson Addison-Wesley. All rights reserved 5-9Logic of an IF statementconditionevaluatedTrue blocktrue falseFalse ...
© 2004 Pearson Addison-Wesley. All rights reserved 5-10Block Statements• Several statements can be grouped together into a...
© 2004 Pearson Addison-Wesley. All rights reserved 5-11Block Statements• In an IF statement, the if portion, or the elsepo...
© 2004 Pearson Addison-Wesley. All rights reserved 5-12Boolean Expressions• A condition often uses one of Javas equalityop...
© 2004 Pearson Addison-Wesley. All rights reserved 5-13The if Statement• An example of an if statement:if (sum > MAX)delta...
© 2004 Pearson Addison-Wesley. All rights reserved 5-14Indentation• The statement controlled by the if statement isindente...
© 2004 Pearson Addison-Wesley. All rights reserved 5-15The if Statement• What do the following statements do?if (top >= MA...
© 2004 Pearson Addison-Wesley. All rights reserved 5-16Logical Operators: CombiningComparisons Together• Boolean expressio...
© 2004 Pearson Addison-Wesley. All rights reserved 5-17Logical NOT• The logical NOT operation is also called logicalnegati...
© 2004 Pearson Addison-Wesley. All rights reserved 5-18Logical AND Operator• The logical AND expressiona && bis true if bo...
© 2004 Pearson Addison-Wesley. All rights reserved 5-19Logical OR Operator• The logical OR expressiona || bis true if a or...
© 2004 Pearson Addison-Wesley. All rights reserved 5-20Logical Operators• Expressions that use logical operators can formc...
© 2004 Pearson Addison-Wesley. All rights reserved 5-21Short-Circuited Operators• The processing of logical AND and logica...
© 2004 Pearson Addison-Wesley. All rights reserved 5-22Indentation Revisited• Remember that indentation is for the humanre...
© 2004 Pearson Addison-Wesley. All rights reserved 5-23Nested if Statements• The statement executed as a result of an ifst...
© 2004 Pearson Addison-Wesley. All rights reserved 5-24The SWITCH Statement• The switch statement provides another way tod...
© 2004 Pearson Addison-Wesley. All rights reserved 5-25The SWITCH Statement• The general syntax of a switch statement is:s...
© 2004 Pearson Addison-Wesley. All rights reserved 5-26The switch Statement• Often a break statement is used as the lastst...
© 2004 Pearson Addison-Wesley. All rights reserved 5-27The switch Statementswitch (option){case A:aCount++;break;case B:bC...
© 2004 Pearson Addison-Wesley. All rights reserved 5-28The switch Statement• A switch statement can have an optional defau...
© 2004 Pearson Addison-Wesley. All rights reserved 5-29The switch Statement• The expression of a switch statement must res...
© 2004 Pearson Addison-Wesley. All rights reserved 5-30OutlineThe if Statement and ConditionsOther Conditional StatementsC...
© 2004 Pearson Addison-Wesley. All rights reserved 5-31Comparing Data• When comparing data using boolean expressions,its i...
© 2004 Pearson Addison-Wesley. All rights reserved 5-32Comparing Float Values• You should rarely use the equality operator...
© 2004 Pearson Addison-Wesley. All rights reserved 5-33Comparing Float Values• To determine the equality of two floats, yo...
© 2004 Pearson Addison-Wesley. All rights reserved 5-34Comparing Characters• As weve discussed, Java character data is bas...
© 2004 Pearson Addison-Wesley. All rights reserved 5-35Comparing Characters• In Unicode, the digit characters (0-9) arecon...
© 2004 Pearson Addison-Wesley. All rights reserved 5-36Comparing Strings• Remember that in Java a character string is anob...
© 2004 Pearson Addison-Wesley. All rights reserved 5-37Comparing Strings• We cannot use the relational operators to compar...
© 2004 Pearson Addison-Wesley. All rights reserved 5-38Comparing Stringsif (name1.compareTo(name2) < 0)System.out.println ...
© 2004 Pearson Addison-Wesley. All rights reserved 5-39Lexicographic Ordering• Lexicographic ordering is not strictly alph...
Upcoming SlideShare
Loading in...5
×

Week03

309

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
309
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Week03"

  1. 1. Week 3ConditionalStatements
  2. 2. © 2004 Pearson Addison-Wesley. All rights reserved 5-2Copyright WarningCOMMONWEALTH OF AUSTRALIACopyright Regulations 1969WARNINGThis material has been copied and communicated to you by oron behalf of Bond University pursuant to Part VB of theCopyright Act 1968 (the Act).The material in this communication may be subject to copyrightunder the Act. Any further copying or communication of thismaterial by you may be the subject of copyright protectionunder the Act.Do not remove this notice.
  3. 3. © 2004 Pearson Addison-Wesley. All rights reserved 5-3Conditional Statements• Now we will examine programming statementsthat allow us to: make decisions perform commands based on those decisions• Chapter 5 focuses on: boolean expressions conditional statements comparing data
  4. 4. © 2004 Pearson Addison-Wesley. All rights reserved 5-4OutlineThe if Statement and ConditionsOther Conditional StatementsComparing Data
  5. 5. © 2004 Pearson Addison-Wesley. All rights reserved 5-5Flow of Control• Unless specified otherwise, the order of statementexecution through a method is linear: onestatement 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 based on boolean expressions(or conditions) that evaluate to true or false• The order of statement execution is called the flowof control
  6. 6. © 2004 Pearson Addison-Wesley. All rights reserved 5-6Conditional Statements• A conditional statement lets us choose whichstatement will be executed next• Therefore they are sometimes called selectionstatements• Conditional statements give us the power tomake basic decisions• The Java conditional statements are the: IF statement SWITCH statement
  7. 7. © 2004 Pearson Addison-Wesley. All rights reserved 5-7The IF Statement• Looks like the followingif ( condition ){statement1;statement2;}else{statement3;statement4;}• If the condition is true, statements 1 & 2 areexecuted; if the condition is false, statements 3& 4 are executed• One section or the other will be executed, but notboth
  8. 8. © 2004 Pearson Addison-Wesley. All rights reserved 5-8The IF Statement• The else { … } section is optional If we dont need to do anything on a false decision, wecan leave it out• Also, if there is only 1 line of code to do in eachsection, we can leave out the curly brackets { }• For example:if ( age < 18 )        System.out.println(“Too young to come in”);
  9. 9. © 2004 Pearson Addison-Wesley. All rights reserved 5-9Logic of an IF statementconditionevaluatedTrue blocktrue falseFalse block
  10. 10. © 2004 Pearson Addison-Wesley. All rights reserved 5-10Block Statements• Several statements can be grouped together into ablock statement delimited by braces• A block statement can be used wherever astatement is called for in the Java syntax rulesif (total > MAX){System.out.println ("Error!!");errorCount++;}
  11. 11. © 2004 Pearson Addison-Wesley. All rights reserved 5-11Block Statements• In an IF statement, the if portion, or the elseportion, or both, could be block statementsif (total > MAX){System.out.println ("Error!!");errorCount++;}else{System.out.println ("Total: " + total);current = total*2;}
  12. 12. © 2004 Pearson Addison-Wesley. All rights reserved 5-12Boolean Expressions• A condition often uses one of Javas equalityoperators or relational operators, which all returnboolean 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 (=)
  13. 13. © 2004 Pearson Addison-Wesley. All rights reserved 5-13The 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 sumis either greater than the value of MAX, or it is not• If the condition is true, the assignment statementis executed -- if it isn’t, it is skipped.• Either way, the call to println is executed next
  14. 14. © 2004 Pearson Addison-Wesley. All rights reserved 5-14Indentation• The statement controlled by the if statement isindented to indicate that relationship• The use of a consistent indentation style makes aprogram easier to read and understand• Although it makes no difference to the compiler,proper indentation is crucial"Always code as if the person who ends upmaintaining your code will be a violentpsychopath who knows where you live."-- Martin Golding
  15. 15. © 2004 Pearson Addison-Wesley. All rights reserved 5-15The if Statement• What do the following statements do?if (top >= MAXIMUM)top = 0;if (total != stock + warehouse)inventoryError = true;• The precedence of the arithmetic operators ishigher than the precedence of the equality andrelational operators
  16. 16. © 2004 Pearson Addison-Wesley. All rights reserved 5-16Logical Operators: CombiningComparisons Together• Boolean expressions can also use the followinglogical operators:! Logical NOT&& Logical AND|| Logical OR• They all take boolean operands and produceboolean results• Logical NOT is a unary operator (it operates onone operand)• Logical AND and logical OR are binary operators(each operates on two operands)
  17. 17. © 2004 Pearson Addison-Wesley. All rights reserved 5-17Logical NOT• The logical NOT operation is also called logicalnegation or logical complement• If some boolean condition a is true, then !a isfalse; if a is false, then !a is true• Logical expressions can be shown using a truthtabletruefalsefalsetrue!aa
  18. 18. © 2004 Pearson Addison-Wesley. All rights reserved 5-18Logical AND Operator• The logical AND expressiona && bis true if both a and b are true, and false otherwise• Example:if ( (x > 10) && (x < 20) )• The whole condition is true if x > 10 AND x < 20AT THE SAME TIME!
  19. 19. © 2004 Pearson Addison-Wesley. All rights reserved 5-19Logical OR Operator• The logical OR expressiona || bis true if a or b or both are true, and falseotherwise• Example:if ( (ch == a) || (ch == A) )• The whole condition is true if ch is either the lettera OR the letter A.
  20. 20. © 2004 Pearson Addison-Wesley. All rights reserved 5-20Logical Operators• Expressions that use logical operators can formcomplex conditionsif (total < MAX+5 && !found)System.out.println ("Processing…");• All logical operators have lower precedence thanthe relational operators• Logical NOT has higher precedence than logicalAND and logical OR• When in doubt, use parentheses to enforce theorder of evaluation
  21. 21. © 2004 Pearson Addison-Wesley. All rights reserved 5-21Short-Circuited Operators• The processing of logical AND and logical OR is“short-circuited”• This is known as lazy evaluation• If the left operand is sufficient to determine theresult, the right operand is not evaluated• This type of processing must be used carefullyif (count != 0 && total/count > MAX)System.out.println ("Testing…");
  22. 22. © 2004 Pearson Addison-Wesley. All rights reserved 5-22Indentation Revisited• Remember that indentation is for the humanreader, and is ignored by the computerif (total > MAX)System.out.println ("Error!!");errorCount++;Despite what is implied by the indentation, theincrement will occur whether the condition istrue or not
  23. 23. © 2004 Pearson Addison-Wesley. All rights reserved 5-23Nested if Statements• The statement executed as a result of an ifstatement or else clause could be another ifstatement• These are called nested if statements• See MinOfThree.java (page 219)• An else clause is matched to the last unmatchedif (no matter what the indentation implies)• Braces can be used to specify the if statement towhich an else clause belongs
  24. 24. © 2004 Pearson Addison-Wesley. All rights reserved 5-24The SWITCH Statement• The switch statement provides another way todecide which statement to execute next• The switch statement evaluates an expression,then attempts to match the result to one of severalpossible cases• Each case contains a value and a list ofstatements• The flow of control transfers to statementassociated with the first case value that matches
  25. 25. © 2004 Pearson Addison-Wesley. All rights reserved 5-25The SWITCH Statement• The general syntax of a switch statement is:switch ( expression ){case value1 :statement-list1case value2 :statement-list2case value3 :statement-list3case ...}switchandcasearereservedwordsIf expressionmatches value2,control jumpsto here
  26. 26. © 2004 Pearson Addison-Wesley. All rights reserved 5-26The switch Statement• Often a break statement is used as the laststatement in each cases statement list• A break statement causes control to transfer tothe end of the switch statement• If a break statement is not used, the flow ofcontrol will continue into the next case• Sometimes this may be appropriate, but often wewant to execute only the statements associatedwith one case
  27. 27. © 2004 Pearson Addison-Wesley. All rights reserved 5-27The switch Statementswitch (option){case A:aCount++;break;case B:bCount++;break;case C:cCount++;break;}• An example of a switch statement:
  28. 28. © 2004 Pearson Addison-Wesley. All rights reserved 5-28The switch Statement• A switch statement can have an optional defaultcase• The default case has no associated value andsimply uses the reserved word default• If the default case is present, control will transferto it if no other case value matches• If there is no default case, and no other valuematches, control falls through to the statementafter the switch
  29. 29. © 2004 Pearson Addison-Wesley. All rights reserved 5-29The switch Statement• The expression of a switch statement must resultin an integral type, meaning an integer (byte,short, int, long) or a char• It cannot be a boolean value or a floating pointvalue (float or double)• The implicit boolean condition in a switchstatement is equality• You cannot perform relational checks with aswitch statement• See GradeReport.java (page 225)
  30. 30. © 2004 Pearson Addison-Wesley. All rights reserved 5-30OutlineThe if Statement and ConditionsOther Conditional StatementsComparing Data
  31. 31. © 2004 Pearson Addison-Wesley. All rights reserved 5-31Comparing Data• When comparing data using boolean expressions,its important to understand the nuances of certaindata types• Lets examine some key situations: Comparing floating point values for equality Comparing characters Comparing strings (alphabetical order) Comparing object vs. comparing object references
  32. 32. © 2004 Pearson Addison-Wesley. All rights reserved 5-32Comparing Float Values• You should rarely use the equality operator (==)when comparing two floating point values (floator double)• Two floating point values are equal only if theirunderlying binary representations match exactly• Computations often result in slight differences thatmay be irrelevant• In many situations, you might consider twofloating point numbers to be "close enough" evenif they arent exactly equal
  33. 33. © 2004 Pearson Addison-Wesley. All rights reserved 5-33Comparing Float Values• To determine the equality of two floats, you maywant to use the following technique:if (Math.abs(f1 - f2) < TOLERANCE)System.out.println ("Essentially equal");• If the difference between the two floating pointvalues is less than the tolerance, they areconsidered to be equal• The tolerance could be set to any appropriatelevel, such as 0.000001
  34. 34. © 2004 Pearson Addison-Wesley. All rights reserved 5-34Comparing Characters• As weve discussed, Java character data is basedon the Unicode character set• Unicode establishes a particular numeric value foreach character, and therefore an ordering• We can use relational operators on character databased on this ordering• For example, the character + is less than thecharacter J because it comes before it in theUnicode character set• Appendix C provides an overview of Unicode
  35. 35. © 2004 Pearson Addison-Wesley. All rights reserved 5-35Comparing Characters• In Unicode, the digit characters (0-9) arecontiguous and in order• Likewise, the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order97 through 122a – z65 through 90A – Z48 through 570 – 9Unicode ValuesCharacters
  36. 36. © 2004 Pearson Addison-Wesley. All rights reserved 5-36Comparing Strings• Remember that in Java a character string is anobject• This means that you should not use == to test iftwo strings have the same value• The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order• The equals method returns a boolean resultif (name1.equals(name2))System.out.println ("Same name");
  37. 37. © 2004 Pearson Addison-Wesley. All rights reserved 5-37Comparing Strings• We cannot use the relational operators to comparestrings• The String class contains a method calledcompareTo to determine if one string comesbefore another• A call to name1.compareTo(name2) returns zero if name1 and name2 are equal (contain thesame characters) returns a negative value if name1 is less than name2 returns a positive value if name1 is greater than name2
  38. 38. © 2004 Pearson Addison-Wesley. All rights reserved 5-38Comparing Stringsif (name1.compareTo(name2) < 0)System.out.println (name1 + "comes first");elseif (name1.compareTo(name2) == 0)System.out.println ("Same name");elseSystem.out.println (name2 + "comes first");• Because comparing characters and strings isbased on a character set, it is called alexicographic ordering
  39. 39. © 2004 Pearson Addison-Wesley. All rights reserved 5-39Lexicographic Ordering• Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed• For example, the string "Great" comes before thestring "fantastic" because all of the uppercaseletters come before all of the lowercase letters inUnicode• Also, short strings come before longer stringswith the same prefix (lexicographically)• Therefore "book" comes before "bookcase"
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×