0
Upcoming SlideShare
×

# Week03

309

Published on

Published in: Technology, Education
0 Likes
Statistics
Notes
• Full Name
Comment goes here.

Are you sure you want to Yes No
• Be the first to comment

• Be the first to like this

Views
Total Views
309
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
5
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
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”);
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
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)