Download Document

Document related concepts
no text concepts found
Transcript
Unit 4 Control structures
Content
1.
2.
3.
4.
5.
6.
statements execution order & flow of control (FOC)
relational expressions
Branching control structures
Looping control structures
Single-entry-single-exit principle
debugging techniques
1
1) Order of executing program statements
 Program Execution Order
 Generally, we have only one CPU
 Therefore, program statements are executed one-by-one
sequentially
 sequence of statement execution called Flow of Control
(FoC)
 Fixed sequence is not desirable
 Jump to another function
 Jump to other statements under some conditions
 Loop a set of statements
2
Program Execution Order
 For example,
 Check username match password. If success, provides
services.
 Otherwise, rejects it.
Flow of Control
 In all programming language, foc includes
Expression to determine the flow
Branching mechanism e.g. if-else, goto
Looping mechanism e.g. for, while
 Java also provides its own mechanisms
3
2) Relational Expressions
 An expression is the condition to determine the flow in
runtime
 An expression returns true or false ( > 0 or <= 0 )
 An expression consists of operators:
 Arithmetic operators [+ , - ,* , / , % , ^ , += , -= ,*=, /= ]
 relational operators [< , > , <= , >= ]
 Assignment operators [ = ]
 Unary operators [ -aNumber ]
 Result of operators depends on LHS and/or RHS values
 Primitive type, reference variable, constant and even
method return value
4
Java Expression
 In Java, an expression can have no operator
 A variable
 Return value of a method call
 Boolean or integer
 if (stop)
 if (obj)
 if (isValid(obj))
 If integer,
 how does the branching/looping evaluate as true
or false ?
 How about float or object ?
5
Relational Operators
 Evaluate and return true or false
 6 Relational Operators,
 for example : testing for A < B,
 when A=1 and B=2, the result is true
 when A=2 and B=1, the result is false
 Can be used for all numeric primitive :
 [ byte , short , char, int , long , float & double
]
6
Operators
Relational
Equality
7
Equality Operators == & !=
 == & != can be used for reference variables
 If you are new in programming, must pay attention to the
2 operators == & !=
 != means not equal
 The exclamation mark (!) in Java always means
'negation' or 'not'
 == is equal
8
"==" (equality) VS "=" (assignment)
int a = 1, b = 2 ;
if (a == b) {
}
if (a = b) {
// This block will NOT be executed?
// This block will be executed
}
 the latter expression results in a = 2 & the second
block will be executed
 because "=" is assignment, totally different from "=="
9
Example
 Java compiler
will detect this
error before
execution
public class compilationError {
public static void main (String args[]) {
final int MY_CONSTANT = 10 ;
int a = 5 ;
if (MY_CONSTANT == a) {
System.out.println("It is OK");
}
if (MY_CONSTANT = a) {
System.out.println("it is Not OK");
}
}
}
C:\>javac compilationError.java
a.java:8: cannot assign a value to final variable MY_CONSTANT
if (MY_CONSTANT = a) {
^
1 error
10
Integer & Floating Point
 Operators are reliable for integer but not for floating point
 Floating point calculation results are also just
approximations because of rounding-off
 Therefore,
 a / b * b == a ?
 a == 0.85 ?
 Using Math.abs(a – 0.85) < 0.0000001
 where 0.0000001 is an arbitrary value of the tolerable
round-off error
11
Operator == and Reference Variables
 Operators == can be applied for reference variables
 But the result…
 In unit 3, reference variables actually carry the locations
of objects
 So, == compares the locations rather than the states of
the objects
 Means they refer to the same object
12
Fig 4.2 pp-9
Case studies about
the results of :
(counter1 == counter2)
13
14
Customize Method equals()
 Want to compare the states of objects
 Using method equals() instead of == operator
 Class must implement its own equals()
 Default implemented in java.lang.Object
 The default implemented is just like ==
 For example,
 class String override to compare the content of char buffer
 So, don’t relay on default equals()
(p-11) : s1.equals(s2) returns false
King-130 :
 (s1==s2) and s1.equals(s2)
returns true only when
different
15
Precedence and Associativity




Determine the order in an expressions
Higher precedence are performed first
When same precedence, using associativity
Arithmetic operators has higher precedence
 relational, in turn higher precedence than
 equality operators
 remember the table ( next page ) or always using
parentheses "()" in expression
 suggest to use "()"
16
Precedence
Associativity
Remarks
+ -
Right
Unary operators
* / %
Left
+ -
Left
>= > < <=
Left
== !=
Left
= += -= *=
Right
/= %=
 "+=" means InCrement
 "-=" means DeCrement
Assignment operators
 Why assignment is lowest?
 Don’t forget that the "!" operator means negation
17
Self-test 4.1
Evaluate the following :
a) 5 + 4 / 3 * 2
b) (3 + 2) * 4
c) 33 * 3 < 99
d) (4 + 3) * 2 != 12
Answer :
a) 7
b) 20
c) false
d) true
18
3) Branching
 Now you know expression and operators
 After evaluating a condition (an expression in Java),
the flow depends on the Branching or Looping
statement
 The java programming language only supports two
branching structures,
 if/else statement
 switch/case statement
19
if Statement
20
if Statement
 If sth is true, then the extra block of statement will be
executed
 The condition in the parentheses must be an
expression return true or false
 The statements enclosed in the curly brackets "{"
and "}" are executed
 Besides the coding, you must also know the flow
chart
21
Curly brackets
 Curly brackets, "{" and "}", must be in pair
 Although curly brackets is not a must, highly
recommended to use for maintenance
if (condition)
statement-1;
statement-2;
is interpreted as
if (condition)
statement-1;
statement-2;
22
Indention in Statement Block
 Usually indent the statements in a block so that
 Easier to identify the block properly & enhance
the readability
 Not only in if, but also all block like function body
23
P.25 MinMaxFinder.java
public class MinMaxFinder {
private int currentMin = Integer.MAX_VALUE; // the current minimum
private int currentMax = Integer.MIN_VALUE; // the current maximum
// Present a number to the object for testing with current minimum and maximum
public void testNumber(int number) {
// Compare the given number with current maximum
if (number > currentMax) {
currentMax = number;
If the given number is greater than current maximum
}
then assign the given number to the current maximum
// Compare the given number with the current minimum
if (number < currentMin) {
currentMin = number;
If the given number is less than the current mininum
}
then assign the given number to the current minimum
}
// retrieve the current minimum
public int getMinimum() { return currentMin; }
// retrieve the current maximum
public int getMaximum() { return currentMax; }
24
}
P.28 TestMinMaxFinder.java (driver program)
public class TestMinMaxFinder {
public static void main(String args[]) {
MinMaxFinder finder = new MinMaxFinder();
// Sending messages with numbers to the object so that
// the numbers are tested one by one
finder.testNumber(15);
finder.testNumber(20);
finder.testNumber(10);
// Send messages to the object to get its current min & max value
int minNumber = finder.getMinimum();
int maxNumber = finder.getMaximum();
System.out.println("Minimum number = " + minNumber);
System.out.println("Maximum number = " + maxNumber);
}
}
25
P.32 GreetingChooser.java
public class GreetingChooser {
// Determine the greeting based on the given hour
public String assignGreeting (int hour) {
// A local variable for storing the result temporarily
String greeting = "";
if (hour >= 0) { greeting = "morning"; }
if (hour >= 12){ greeting = "afternoon"; }
if (hour >= 18){ greeting = "evening";}
// Return the result to the caller
return greeting;
}
}
26
P.34 TestGreeting.java ( driver program )
import javax.swing.JOptionPane;
public class TestGreeting {
public static void main(String args[]) {
GreetingChooser chooser = new GreetingChooser();
// Show a dialog to get the hour from user
// The obtained hour is returned as a String object
String inputHour =
JOptionPane.showInputDialog("Please enter the hour");
// Obtain the integer value from the input String object
int hour = Integer.parseInt(inputHour);
String greeting = chooser.assignGreeting(hour);
String output = "Good " + greeting;
// set the message to be shown
JOptionPane.showMessageDialog(null, output);// Show greeting with a dialog
System.exit(0);
// Terminate the program
}
27
}
Mutually Exclusive
 In the situation,
 Perform a task if a condition is true
 Otherwise, perform another task
 It works but suffers from performance penalty
because of 2 test
if (number > 0) {
System.out.println("Number is positive");
}
else {
System.out.println("Number is non-positive");
}
Print a line & then
start a new line
28
if/else Statement
 Java extends if by optional else statement(s)
 Support any number of else statements
if (condition) {
statement(s)-1 // statement(s) to be executed if the condition is true
}
else {
statement(s)-2 // statement(s) to be executed if the condition is false
}
statement(s)-1
(if part)
true
condition
false
statement(s)-2
(else part)
29
switch/case Statement
 Sometimes, it is necessary to test the content of a variable
against a list of possible values
 Can use a number of if..else if..else
 But coding is tedious
 Java provides a faster and more readable flow of control
statement:
 switch / case
30
switch/case Statement
“default” is optional
(p64~65)
“break” means end of a case
 If missing, run next statement
 Recommend to use
 Recommend to use
 catch unexpected conditions
switch (expr) {
case expr-1:
statements-1;
expr ==
break;
expr-1
case expr-2:
false
statements-2;
expr ==
break;
expr-2
case expr-3:
false
statements-3;
expr ==
break;
expr-3
default:
statements-default;
false
break;
}
true
true
true
statements-1
break
statements-2
break
statements-3
break
statementsdefault
break
31
switch/case vs if/else
 switch/case can support primitive type of :
 byte, short, char and int only
 can check the equality for byte, short, char or int
 only supports equality checking
 if/else can support boolean type only
 with proper relational operators, can support all
primitive type and non-primitive type
 can check the equality for long, float, double,
boolean and non-primitive types
 can use any relational operator.
32
switch/case vs if/else
 Although switch/case is more restricted,
 Its structure is more elegant and easier to read
 Faster
 Use it whenever possible
33
Example
// page 58
// page 71
public class GradeConverter {
public String assignGrade(int mark) {
// The grade is first assumed to be F
String grade = "F";
public class GradeConverter2 {
public String assignGrade(int mark) {
// The grade to be returned
String grade;
// Set criteria for grades one by one
if (mark >= 50) {grade = "E"; }
if (mark >= 60) {grade = "D"; }
if (mark >= 70) {grade = "C"; }
if (mark >= 80) {grade = "B"; }
if (mark >= 90) {grade = "A"; }
// Set criteria for grades one by one
switch (mark / 10) {
case 9: case 10: grade = "A";
case 8:
grade = "B";
case 7:
grade = "C";
case 6:
grade = "D";
case 5:
grade = "E";
default:
grade = "F";
}
// Return the determined grade
return grade;
break;
break;
break;
break;
break;
break;
}
}
// Return the determined grade
return grade;
}
}
34
4) Looping control structures
 In many cases, a program needs to
execute the same statement several
times
 eg. calculate total number of staff
salaries
 Therefore, programming language must support
looping
 Java defines 3 types:
 while
 do/while
 for
35
Looping
 usually a loop has of 2 parts
 Condition
 Statement/loop body
 Furthermore,
 Initialization
 Update
 Finally,
 Execute-check or
 check-execute
 Anyway, don’t make an
infinite looping
 A loop never ends
 Condition always true
 P.99 even server side check
exit/stop event
 Famous loop:
 Windows GUI event loop
 Palm event loop
 Web server event loop
36
while Loop
while (codition)
statement(s)
General
format
condition
true
statement(s)
false
while (condition) {
statement(s)
}
37
while Loop
 Clear definition for Condition & Statement/loop body
 No definition for Initialization & Update
 Check-execute
 The loop body can be completely ignored
 Simple, suitable for loops require no initialization and
update
 E.g. GUI event loops, JDBC result set
38
Example
(page 75~76)
// example-1
i = 1;
n = 10;
while (i < n)
i *= 2;
// example-2 (recommended)
i = 1;
n = 10;
while (i < n) {
i *= 2;
}
i = 1;
n = 10;
i < n
true
i *= 2
false
39
Table 4.4 Execution details of a loop
(p-77)
Value
of
Value
of
Value
of
Iteration
i
n
i < n
Actions to be taken
1
1
10
true
The loop body is executed, and the value
of variable i becomes 2.
2
2
10
true
The loop body is executed, and the value
of variable i becomes 4.
3
4
10
true
The loop body is executed, and the value
of variable i becomes 8.
4
8
10
true
The loop body is executed, and the value
of variable i becomes 16.
5
16
10
false
The loop is terminated
As a result, the value of the variable i is 16 when the loop is terminated.
40
do/while Loop
(p-81)
do
statement
statement(s)
while (condition);
condition
do
statement
true
false
while (condition);
do {
statement(s)
} while (condition);
41
do/while Loop
 Just like while loop
 Execute-check instead check-execute
 The loop body will be executed at least once
 Sometimes, initialization is embedded in the loop
body
42
Self-Test 4.5
(p-126)
result = result * number ;
eg. 4! = 4x3x2
// a buggy version of factorial
public int factorial(int number) {
int result = 1;
do {
result *= number;
number-- ;
} while (number > 1) ;
return result ;
}
// a correct version of factorial
public int factorial(int number) {
int result = 1;
while (number > 1) {
result *= number;
number-- ;
}
return result ;
}
Do / While
 when input <= 1
 loop body runs to return 0
 thus, 0! = 0 ( which is wrong)
While
 when input <= 1
 loop body skipped & return
the default, 1
43
 thus, 0! = 1 and (-1)! = 1
for Loop
44
for Loop
 Clear definition for Condition &
Statement/loop body
 Clear definition for Initialization &
Update
 Check-execute like while
 Difficult to read
 Initialization, Condition & Update
are in the same stement
 Suitable for numerical loops
45
for = while
 Which is more preferable?
 If explicit initialization/update are required, for is
more suitable (eg. loop all elements in a collection)
 otherwise, while (eg. loop all result set of a JDBC call)
46
Example for for & while
java.util.Vector vec =
new java.util.Vector(10) ;
// update the vec
java.sql.ResultSet rs = null ;
for (int i = 0; i < vec.size(); i++) {
java.lang.Object obj =
vec.get(i) ;
// process the obj
}
while (rs.next()) {
rs.getString(1) ;
// process the result set item
// update the result set
}
47
Start from Zero
 A for loop uses an integer as index to a collection
 the start value is 0 instead of 1
 Thus, condition uses "<" instead of "<="
 Beginner must be careful
 This introduce a lot of misunderstanding in programming
 eg. ResultSet
48
Practice and Scope
 Although meaningful variable names are
recommended, there is an exception case
 In for loop, the index always use
simple char like j, k…
 This is an acceptable exception in
programming
 Due to scope (life time of a variable), such declared
variables cannot be reused outside the loop
 Each loop has its own
49
Unintentional Infinite Loop
(p-102)
 Loop condition is always true
 Pls heed the data type limitation
 Max/min values
 Default value
 Logical error
 Debug message
Integer.MAX_VALUE = 32767
50
5) Single-entry-single-exit principle
(p102~3)
break / return / continue / goto
 Flow of control should be kept simple & straight-forward
 Therefore, don't use goto (no longer supported) and
continue to jump to another segment
 Also, keep break and return as less as possible in a
method or a loop
51
Which is more preferable ?
public int factorial(int number) {
if (number < 0) {
return -1;
}
(p104)
public int factorial(int number) {
int result;
if (number < 0) {
result = -1;
}
else {
result = 1;
for (int i = number; i > 1; i--) {
result *= i;
}
}
int result = 1;
for (int i = number; i > 1; i--) {
result *= i;
}
return result;
}
// earlier & multiple exit points
// by using TWO return statements
return result;
}
// unique exit
// by using ONE return statement
52
Which is more preferable ?
public String assignGrade(int mark) {
String grade = "";
switch (mark / 10) {
......
case 9:
if (mark % 10 < 5) {
grade = "A-";
break;
}
grade = "A";
break;
case 10:
grade = "A+";
break;
}
return grade;
}
// not clear
(p105)
public String assignGrade(int mark) {
String grade = "";
switch (mark / 10) {
......
case 9:
if (mark % 10 < 5) {
grade = "A-";
}
else {
grade = "A";
}
break;
case 10:
grade = "A+";
break;
}
return grade;
}
// more clear, but should avoid
53
Exception
 To serve the purpose of single exit, a lot of if-else
statements are used
 programmers find it undesirable for :
 Difficult to follow
 More coding
 That’s why we need exception, to throw an abnormal
situation to the handler directly
 The foc focuses only the normal case
54
Exception Example
try {
String
number = new String("ABC");
java.lang.Integer anInteger=new java.lang.Integer(number);
int
value = anInteger.intValue();
}
catch (NumberFormatException ex) {
// handle numberic exception
}
catch (NullPointerException ex) {
// handle null ptr exception
}
55
Non-exception Example
String number = new String("ABC");
if (null != number) {
if (IcheckNumber(number)) {
int value = convertNumber(number) ;
} else {
// handle numberic
}
} else {
// handle null ptr
}
56
6) Debugging Programs
 Java or IDE Debugger
 More popular - Print message
System.out.println()
System.err.println()
 Not a good approach
 Not persistent
 Add/Remove must re-compile the src
 Log4J – configure logging dynamically
57
Debugging with System.out.println()
while (remainDigits > 0) {
// Get the least significant digit
int digit = remainDigits % 10;
// Print the digit
System.out.println(digit);
// Dropping the last digit
remainDigits /= 10;
}
while (remainDigits > 0) {
// Get the least significant digit
int digit = remainDigits % 10;
// Print the digit
System.out.println(digit);
// Dropping the last digit
remainDigits = 10;
}
the "/" char
is missing
58
println( ) and print( )
public class List7 {
public boolean is7 (int number) {
boolean result = false;
for ( int i=2; I < number; i++ ) {
if (number % 7 == 0) {
result = true;
}
}
return result;
}
}
public class List7Driver {
public static void main(String args[]){
List7 tester = new List7();
for (int i=2; i <= 50; i++) {
if ( tester.is7(i) ) {
System.out.print(i+"\t");
}
"\t" is a <TAB>
character
start at a
}
new line
System.out.println();
System.out.println("Done"); }
}
59
Log4J
 Free java package
 4 level logging
 debug (lowest), info, warn, error
 Configure file defines runtime log level for a package
or a class
 Lower level message not logged in runtime
 Therefore, can determine runtime log message
without recompile of program
60