Comp 248 Introduction to Programming Chapter 3 – Flow of Control Dr. Aiman Hanna Department of...
-
Upload
edmund-clark -
Category
Documents
-
view
215 -
download
0
Transcript of Comp 248 Introduction to Programming Chapter 3 – Flow of Control Dr. Aiman Hanna Department of...
Comp 248 Introduction to Programming Chapter 3 – Flow of Control
Dr. Aiman HannaDepartment of Computer Science & Software Engineering
Concordia University, Montreal, Canada
These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by
Pearson Education / Addison-Wesley.
Copyright © 2007 Pearson Addison-WesleyCopyright © 2008-2013 Aiman Hanna
All rights reserved
Flow of ControlFlow of Control flow of controlflow of control in Java refers to its in Java refers to its
branchingbranching and and loopinglooping
Several branching mechanisms: Several branching mechanisms: if-elseif-else,, ifif,, and and switchswitch statements statements
Three types of loops: Three types of loops: whilewhile, , do-whiledo-while, and , and forfor statementsstatements
Most branching and looping statements are Most branching and looping statements are controlled by Boolean expressionscontrolled by Boolean expressions A Boolean expression evaluates to either A Boolean expression evaluates to either truetrue or or falsefalse
3-2
The The ifif Statement Statement
3-3
if ( condition ) statement;
if is a Javareserved 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.
The The ifif Statement Statement
3-4
Example:Example:
if (x > 10)if (x > 10)
System.out.println(“Hello”);System.out.println(“Hello”);
Compound StatementsCompound Statements
Compound StatementCompound Statement: If the statement : If the statement underunder if if is made up of more than one is made up of more than one statement, they must be enclosed in curly statement, they must be enclosed in curly braces (braces ({ }{ }))
Example:Example:if (amount < balance)if (amount < balance)
{{
System.out.println(“Thank you. Withdrawal will take place”);System.out.println(“Thank you. Withdrawal will take place”);
balance = balance – amount;balance = balance – amount;
}}
3-5
Statements2.java ((MS-Word file))
Statements1.java ((MS-Word file))
if-elseif-else Statement Statement
An An if-elseif-else statement chooses between two statement chooses between two alternative statements based on the value of a alternative statements based on the value of a Boolean expressionBoolean expression
if (if (Boolean_ExpressionBoolean_Expression)) Yes_StatementYes_Statementelseelse No_StatementNo_Statement
Example:Example:
if (x > 10)if (x > 10)System.out.println(“Hello”);System.out.println(“Hello”);
else else System.out.println(“Hi”);System.out.println(“Hi”);
3-6
Compound StatementsCompound Statements Compound StatementCompound Statement: Same rule; multiple : Same rule; multiple
statements must be enclosed in curly braces (statements must be enclosed in curly braces ({ }{ }))Example:Example:
if (amount < balance)if (amount < balance){{
System.out.println(“Thank you. Withdrawal will take System.out.println(“Thank you. Withdrawal will take place”);place”);balance = balance – amount;balance = balance – amount;
}}
else {else {System.out.println(“Sorry. You do not have enough System.out.println(“Sorry. You do not have enough fund.”);fund.”);System.out.println(“Transaction will be cancelled!.”);System.out.println(“Transaction will be cancelled!.”);
}}3-7
Statements3.java ((MS-Word file))
Nested StatementsNested Statements
Statements within Statements within if-elseif-else or or ifif statements can themselves be another statements can themselves be another if-if-elseelse or or ifif statements statements
For clarity, each level of a nested For clarity, each level of a nested if-elseif-else or or ifif should be indented further than the should be indented further than the previous levelprevious level
3-8
Statements4.java ((MS-Word file))
Multiway Multiway ifif--elseelse StatementsStatements
The multiway The multiway if-elseif-else statement is simply a statement is simply a normal normal if-elseif-else statement that nests another statement that nests another if-if-elseelse statement at every statement at every elseelse branch branch
The The Boolean_ExpressionsBoolean_Expressions are evaluated in order until are evaluated in order until one that evaluates to one that evaluates to truetrue is found is found
The final The final elseelse is optional is optional
3-9
Statements5.java ((MS-Word file))
Statements6.java ((MS-Word file))
The The switchswitch Statement Statement
3-10
The general syntax of a switch The general syntax of a switch statement is:statement is:
switch ( expression ){ case value1 : statement-list1
break; case value2 : statement-list2
break; case value3 : statement-list3
break; case ...
default: default-statement
}
switchcaseand
Breakare
reservedwords
If expressionmatches value2,control jumpsto here
Optional
The The switchswitch Statement Statement
3-11
Statements7.java ((MS-Word file))
Statements7B.java ((MS-Word file))
The Conditional OperatorThe Conditional Operator
3-12
The The conditional operatorconditional operator is a notational variant on certain is a notational variant on certain forms of the forms of the if-elseif-else statement statement
Also called the Also called the ternary operatorternary operator or or arithmetic ifarithmetic if
The following examples are equivalent:The following examples are equivalent:
if (n1 > n2) max = n1; if (n1 > n2) max = n1;
else max = n2;else max = n2;
vs.vs.max = (n1 > n2) ? n1 : n2;max = (n1 > n2) ? n1 : n2;
Java Comparison Java Comparison OperatorsOperators
3-13
Pitfall: Using Pitfall: Using ==== with with StringsStrings
The equality comparison operator (The equality comparison operator (====)) can can correctly test two values of a correctly test two values of a primitiveprimitive type type
In order to test two strings to see if they have In order to test two strings to see if they have equal values, use the method equal values, use the method equalsequals, or , or equalsIgnoreCaseequalsIgnoreCase
s1.equals(s2)s1.equals(s2)s1.equalsIgnoreCase(s2)s1.equalsIgnoreCase(s2)
3-14
Lexicographic and Alphabetical Lexicographic and Alphabetical OrderOrder
Lexicographic Lexicographic ordering is the same as ordering is the same as ASCIIASCII ordering, ordering, and includes letters, numbers, and other charactersand includes letters, numbers, and other characters All uppercase letters are in alphabetic order, and all All uppercase letters are in alphabetic order, and all
lowercase letters are in alphabetic order, but all lowercase letters are in alphabetic order, but all uppercase letters come before lowercase lettersuppercase letters come before lowercase letters
If If s1s1 and and s2s2 are two variables of type are two variables of type StringString that have that have been given been given StringString values, then values, then s1.compareTo(s2)s1.compareTo(s2) returns a negative number if returns a negative number if s1s1 comes before comes before s2s2 in in lexicographic ordering, returns zero if the two strings lexicographic ordering, returns zero if the two strings are equal, and returns a positive number if are equal, and returns a positive number if s2s2 comes comes before before s1s1
When performing an alphabetic comparison of strings When performing an alphabetic comparison of strings (rather than a lexicographic comparison) that consist of a (rather than a lexicographic comparison) that consist of a mix of lowercase and uppercase letters, use the mix of lowercase and uppercase letters, use the compareToIgnoreCasecompareToIgnoreCase method instead method instead
3-15
Building Boolean Building Boolean ExpressionsExpressions!! Logical NOTLogical NOT&&&& Logical ANDLogical AND|||| Logical ORLogical OR
3-16
xx !x!x
truetrue falsefalse
falsefalse truetrue
Truth TablesTruth Tables
3-17
xx yy x || yx || y
truetrue truetrue truetrue
truetrue falsefalse truetrue
falsefalse truetrue truetrue
falsefalse falsefalse falsefalse
xx yy x && yx && y
truetrue truetrue truetrue
truetrue falsefalse falsefalse
falsefalse truetrue falsefalse
falsefalse falsefalse falsefalse
Evaluating Boolean Evaluating Boolean ExpressionsExpressions
Boolean expressions can exist independently as Boolean expressions can exist independently as wellwell
boolean madeIt = (time < limit) && (limit < max);boolean madeIt = (time < limit) && (limit < max);
3-18
Short-Circuit and Complete Short-Circuit and Complete EvaluationEvaluation
Java can take a shortcut when the evaluation of the Java can take a shortcut when the evaluation of the first part of a Boolean expression produces a result first part of a Boolean expression produces a result that evaluation of the second part cannot changethat evaluation of the second part cannot change
This is called This is called short-circuit evaluationshort-circuit evaluation or or lazy lazy evaluationevaluation
Example:Example:int x = 10, y = 15;int x = 10, y = 15;
if (x < 4 && y == 15)if (x < 4 && y == 15) // y == 15 will NOT be // y == 15 will NOT be evaluatedevaluated{{
…….... }}
3-19
Short-Circuit and Complete Short-Circuit and Complete EvaluationEvaluation
There are times when using short-circuit There are times when using short-circuit evaluation can prevent a evaluation can prevent a runtime errorruntime error In the following example, if the number of In the following example, if the number of kidskids is equal is equal
to zero, then the second subexpression will not be to zero, then the second subexpression will not be evaluated, thus preventing a evaluated, thus preventing a divide by zero errordivide by zero error
Note that reversing the order of the subexpressions will Note that reversing the order of the subexpressions will not prevent thisnot prevent this
if ((kids !=0) && ((toys/kids) >=2)) . . .if ((kids !=0) && ((toys/kids) >=2)) . . .
Sometimes it is preferable to always evaluate Sometimes it is preferable to always evaluate both expressions, i.e., request complete both expressions, i.e., request complete evaluation evaluation In this case, use the In this case, use the && and and || operators instead of operators instead of &&&& and and ||||
3-20
Precedence and Precedence and Associativity RulesAssociativity Rules
Boolean and arithmetic expressions need not be Boolean and arithmetic expressions need not be fully parenthesizedfully parenthesized
If some or all of the parentheses are omitted, If some or all of the parentheses are omitted, Java will follow Java will follow precedenceprecedence and and associativityassociativity rules rules
3-21
PrecedencPrecedence and e and
AssociativiAssociativity Rulesty Rules
3-22
LoopsLoops
Java has three types of loop statements: Java has three types of loop statements:
the the while while statements statements the the do-while do-while statements statements the the forfor statement statement
3-23
whilewhile statement statement
3-24
The The while statementwhile statement has the has the following syntax:following syntax:
while ( condition ) statement;
while is areserved word
If the condition is true, the statement is executed.Then the condition is evaluated again.
The statement is executed repeatedly untilthe condition becomes false.
whilewhile Syntax Syntax
. . .
3-25
while (Boolean_Expression)while (Boolean_Expression) StatementStatement Or, in the case where there are multiple Or, in the case where there are multiple
statements statements
while (Boolean_Expression)while (Boolean_Expression){{ Statement_1Statement_1 Statement_2Statement_2 … …
}} Statements8.java ((MS-Word file))
Statements9.java ((MS-Word file))
do-whiledo-while Statement Statement
3-26
The The do-while statementdo-while statement has the has the following syntax:following syntax:
do{ statement;}while ( condition )
do andwhile arereserved
words
The statement is executed once initially,and then the condition is evaluated
The statement is executed repeatedlyuntil the condition becomes false
Statements10.java ((MS-Word file))
The The forfor Statement Statement
3-27
The The for statementfor statement has the following has the following syntax:syntax:
for ( initialization ; condition ; increment ) statement;
Reservedword
The initializationis executed once
before the loop begins
The statement isexecuted until the
condition becomes false
The increment portion is executed at the end of each iterationThe condition-statement-increment cycle is executed repeatedly
forfor Statement Syntax and Statement Syntax and Alternate SemanticsAlternate Semantics
3-28
Examples:Examples: for (i=0; i <= 10; i++)for (i=0; i <= 10; i++)
System.out.println(“Hello”);System.out.println(“Hello”);
Or, in the case where there are multiple Or, in the case where there are multiple statementsstatements
for (num=100; num > 0; num = num - 20)for (num=100; num > 0; num = num - 20){{ System.out.println(“looping”); System.out.println(“looping”);
System.out.println(“num is :” + num);System.out.println(“num is :” + num);}}
Statements12.java Statements12.java (MS-Word file)(MS-Word file)
Statements11.java Statements11.java (MS-Word file)(MS-Word file)
Nested LoopsNested Loops Loops can be Loops can be nestednested, just like other Java , just like other Java
structuresstructures When nested, the inner loop iterates from beginning to When nested, the inner loop iterates from beginning to
end for each single iteration of the outer loopend for each single iteration of the outer loop
3-29
Statements13.java Statements13.java (MS-Word file)(MS-Word file)
Notice that variables declared inside for Notice that variables declared inside for statement are local to this statement; i.e. they statement are local to this statement; i.e. they cannot be see outside of the statement cannot be see outside of the statement
Statements14.java Statements14.java (MS-Word file)(MS-Word file)
Statements15.java Statements15.java (MS-Word file)(MS-Word file)
The The breakbreak and and continuecontinue Statements Statements The The breakbreak statement consists of the keyword statement consists of the keyword breakbreak followed by a semicolon followed by a semicolon When executed, the When executed, the breakbreak statement ends the statement ends the
nearest enclosing switch or loop statementnearest enclosing switch or loop statement
The The continuecontinue statement consists of the statement consists of the keyword keyword continuecontinue followed by a semicolon followed by a semicolon When executed, the When executed, the continuecontinue statement ends the statement ends the
current loop body iteration of the nearest current loop body iteration of the nearest enclosing loop statementenclosing loop statement
Note that in a Note that in a forfor loop, the loop, the continuecontinue statement statement transfers control to the transfers control to the updateupdate expression expression
When loop statements are nested, remember When loop statements are nested, remember that anythat any breakbreak or or continuecontinue statement applies statement applies to the innermost, containing loop statementto the innermost, containing loop statement
3-30
Statements16.java Statements16.java (MS-Word file)(MS-Word file)
The Labeled The Labeled breakbreak StatementStatement There is a type of There is a type of breakbreak statement that, statement that,
when used in nested loops, can end any when used in nested loops, can end any containing loop, not just the innermost loopcontaining loop, not just the innermost loop
If an enclosing loop statement is labeled If an enclosing loop statement is labeled with an with an Identifier, Identifier, then the following version then the following version of the break statement will exit the labeled of the break statement will exit the labeled loop, even if it is not the innermost enclosing loop, even if it is not the innermost enclosing loop:loop:break someIdentifier;break someIdentifier;
To label a loop, simply precede it with an To label a loop, simply precede it with an IdentifierIdentifier and a colon: and a colon:someIdentifier:someIdentifier:
3-31
The The exitexit Statement Statement A A breakbreak statement will end a loop or statement will end a loop or
switch statement, but will not end the switch statement, but will not end the programprogram
The The exitexit statement will immediately end statement will immediately end the program as soon as it is invoked:the program as soon as it is invoked:System.exit(0);System.exit(0);
The The exitexit statement takes one integer statement takes one integer argumentargument By tradition, a zero argument is used to By tradition, a zero argument is used to
indicate a normal ending of the programindicate a normal ending of the program
3-32
General Debugging General Debugging TechniquesTechniques
Examine the system as a whole – don’t Examine the system as a whole – don’t assume the bug occurs in one particular placeassume the bug occurs in one particular place
Try different test cases and check the input Try different test cases and check the input valuesvalues
Comment out blocks of code to narrow down Comment out blocks of code to narrow down the offending codethe offending code
Check common pitfallsCheck common pitfalls Take a break and come back laterTake a break and come back later DO NOT make random changes just hoping DO NOT make random changes just hoping
that the change will fix the problem! that the change will fix the problem!
3-33
Debugging Example (1 of Debugging Example (1 of 9)9)
The following code is supposed to The following code is supposed to present a menu and get user input present a menu and get user input until either ‘a’ or ‘b’ is entered.until either ‘a’ or ‘b’ is entered.
3-34
String s = "";char c = ' ';Scanner keyboard = new Scanner(System.in);
do{ System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); s.toLowerCase(); c = s.substring(0,1);}while ((c != 'a') || (c != 'b'));
Debugging Example (2 of Debugging Example (2 of 9)9)
Using the “random change” debugging Using the “random change” debugging technique we might try to change the technique we might try to change the data type of data type of cc to to StringString, to make the , to make the types matchtypes match
This results in more errors since the This results in more errors since the rest of the code treats rest of the code treats cc like a like a charchar
3-35
Result: Syntax error:
c = s.substring(0,1); : incompatible types found: java.lang.String required: char
Debugging Example (3 of Debugging Example (3 of 9)9)
First problem: substring returns a First problem: substring returns a String, use charAt to get the first String, use charAt to get the first character:character:
3-36
String s = "";char c = ' ';Scanner keyboard = new Scanner(System.in);
do{ System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); s.toLowerCase(); c = s.charAt(0);}while ((c != 'a') || (c != 'b'));
Now the program compiles, but it is stuck in an infinite loop. Employ tracing:
Debugging Example (4 of Debugging Example (4 of 9)9)
3-37
do{ System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); System.out.println("String s = " + s); s.toLowerCase(); System.out.println("Lowercase s = " + s); c = s.charAt(0); System.out.println("c = " + c);}while ((c != 'a') || (c != 'b'));
Sample output:Enter 'A' for option A or 'B' for option B.AString s = ALowercase s = Ac = AEnter 'A' for option A or 'B' for option B.
From tracing we can see that the string is never changed to lowercase.Reassign the lowercase string back to s.
Debugging Example (5 of Debugging Example (5 of 9)9)
The following code is supposed to The following code is supposed to present a menu and get user input present a menu and get user input until either ‘a’ or ‘b’ is entered.until either ‘a’ or ‘b’ is entered.
3-38
do{ System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); s = s.toLowerCase(); c = s.charAt(0);}while ((c != 'a') || (c != 'b'));
However, it’s still stuck in an infinite loop. What to try next?
Debugging Example (6 of Debugging Example (6 of 9)9)
Could try the following “patch”Could try the following “patch”
3-39
do{ System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); s = s.toLowerCase(); c = s.charAt(0); if ( c == 'a') break; if (c == 'b')
break;}while ((c != 'a') || (c != 'b'));
This works, but it is ugly! Considered a coding atrocity, it doesn’t fix theunderlying problem. The boolean condition after the while loop has alsobecome meaningless. Try more tracing:
Debugging Example (7 of Debugging Example (7 of 9)9)
3-40
do{ System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); s = s.toLowerCase(); c = s.charAt(0); System.out.println("c != 'a' is " + (c != 'a')); System.out.println("c != 'b' is " + (c != 'b')); System.out.println("(c != 'a') || (c != 'b')) is "
+ ((c != 'a') || (c != 'b')));}while ((c != 'a') || (c != 'b'));
Sample output:Enter 'A' for option A or 'B' for option B.Ac != 'a' is falsec != 'b' is true(c != 'a') || (c != 'b')) is true
From the trace we can see that the loop’s boolean expression is true because ccannot be not equal to ‘a’ and not equal to ‘b’ at the same time.
Debugging Example (8 of Debugging Example (8 of 9)9)
Fix: We use && instead of ||Fix: We use && instead of ||
3-41
do{ System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); s = s.toLowerCase(); c = s.charAt(0);}while ((c != 'a') && (c != 'b'));
Debugging Example (9 of Debugging Example (9 of 9)9)
Alternative Solution: Declare a boolean Alternative Solution: Declare a boolean variable to control the do-while loop. This variable to control the do-while loop. This makes it clear when the loop exits if we makes it clear when the loop exits if we pick a meaningful variable name.pick a meaningful variable name.
3-42
boolean invalidKey;do{ System.out.println("Enter 'A' for option A or 'B' for option B."); s = keyboard.next(); s = s.toLowerCase(); c = s.charAt(0); if (c == 'a')
invalidKey = false; else if (c == 'b')
invalidKey = false; else
invalidKey = true;}while (invalidKey);
Assertion ChecksAssertion Checks An An assertionassertion is a sentence that says (asserts) is a sentence that says (asserts)
something about the state of a programsomething about the state of a program An assertion must be either true or false, and should be An assertion must be either true or false, and should be
true if a program is working properlytrue if a program is working properly Assertions can be placed in a program as commentsAssertions can be placed in a program as comments
Java has a statement that can check if an Java has a statement that can check if an assertion is trueassertion is trueassert Boolean_Expression;assert Boolean_Expression; If assertion checking is turned on and the If assertion checking is turned on and the Boolean_ExpressionBoolean_Expression evaluates to evaluates to falsefalse, the program , the program ends, and outputs an ends, and outputs an assertion failed error messageassertion failed error message
Otherwise, the program finishes execution normallyOtherwise, the program finishes execution normally
3-43
Assertion ChecksAssertion Checks A program or other class containing A program or other class containing
assertions is compiled in the usual wayassertions is compiled in the usual way
After compilation, a program can run with After compilation, a program can run with assertion checking turned on or turned offassertion checking turned on or turned off Normally a program runs with assertion Normally a program runs with assertion
checking turned offchecking turned off
In order to run a program with assertion In order to run a program with assertion checking turned on, use the following checking turned on, use the following command (using the actual command (using the actual ProgramNameProgramName):): java –enableassertions ProgramNamejava –enableassertions ProgramName
3-44
Preventive CodingPreventive Coding
Incremental DevelopmentIncremental Development Write a little bit of code at a time and Write a little bit of code at a time and
test it before moving ontest it before moving on Code ReviewCode Review
Have others look at your codeHave others look at your code Pair ProgrammingPair Programming
Programming in a team, one typing Programming in a team, one typing while the other watches, and while the other watches, and periodically switch rolesperiodically switch roles
3-45