topic 03 control statements programming ii/a cmc2522 / cim2561 bavy li
Post on 18-Dec-2015
217 views
TRANSCRIPT
Topic 03Control Statements
Programming II/ACMC2522 / CIM2561
Bavy Li
Background Our problem-solving solutions so far have the
straight-line property
public class DisplayForecast // main(): application entry point
public static void main(String[] args) { System.out.print("I think there is a
world"); System.out.print(" market for maybe five
"); System.out.println("computers. “); System.out.print(" Thomas Watson, IBM, “); System.out.println("1943.“);
}}
Background For general problem solving we need more capabilities
The ability to control which statements are executed The ability to control how often a statement is executed
Java provides the if and switch conditional constructs to control whether a statement list is executed
Java provides the while and for iteration constructs to control whether a statement list is executed
Selection Statements Using if and if...else
Single-selection structure Double-selection structure
Nested if Statements Multiple-selection structure
Using switch Statements
Conditional Operator
Basic if statement Syntax
if (Expression) { Action;
}
If the Expression is true then execute Action
Action is either a single statement or a group of statements (in block) within braces
Expression
Action
true false
Example – Basic if statement
if (value < 0) { value = -value;}
Value < 0
Value = -Value
true false
Is our number negative?
If Value is not less than zero then our number is fine as is
If Value is less than zero then we need to
update its value to that of its additive inverse
Our number is now definitely
nonnegative
Self-Test QuestionSystem.out.print("Enter an integer number: ");int value1 = Integer.parseInt(stdin.readLine());System.out.print("Enter another integer number: ");int value2 = Integer.parseInt(stdin.readLine());
// rearrange numbers if necessaryif (value2 < value1) {
// values are not in sorted orderint rememberValue1 = value1;value1 = value2;value2 = rememberValue1;
}
// display valuesSystem.out.println("The numbers in sorted order are "
+ value1 + " and then " + value2);
What happens if the user enters 11 and 28?
What happens if the user enters 11 and 4?
The if-else statement Syntax
if (Expression) { Action1
}else {
Action2
}
If Expression is true then executeAction1 otherwise execute Action2
Expression
Action1 Action2
true false
Example – Finding maximum values
System.out.print("Enter an integer number: ");int value1 = Integer.parseInt(stdin.readLine());System.out.print("Enter another integer number: ");int value2 = Integer.parseInt(stdin.readLine());
int maximum;if (value1 < value2) { // is value2 larger? maximum = value2; // yes: value2 is larger}else { // (value1 >= value2) maximum = value1; // no: value2 is not larger}System.out.println("The maximum of " + value1
+ " and " + value2 + " is " + maximum);
Example – Finding maximum values
value1 < value2
maximum = value2 maximum = value1
true false
Is value2 larger than value1
Yes, it is . So value2 is larger than value1. In this case, maximum is set to
value2No, its not. So value1 is at least as large as value2. In this case, maximum is set
to value1
Either case, maximum is set correctly
Multiple Alternative if Statements
if (score >= 90) grade = ‘A’;else if (score >= 80) grade = ‘B’; else if (score >= 70) grade = ‘C’; else if (score >= 60) grade = ‘D’; else grade = ‘F’;
if (score >= 90) grade = ‘A’;else if (score >= 80) grade = ‘B’;else if (score >= 70) grade = ‘C’;else if (score >= 60) grade = ‘D’;else grade = ‘F’;
switch statement
switch ( SwitchExpression ) {
case CaseExpression1 :Action1 ;
case CaseExpression2 :Action2 ;
...
case CaseExpressionn :Actionn;
default :Actionn+1 ;
}
Constantintegral
expressionJ avastatements
Integral expression tobe matched with acase expression
Example – Checking vowels
switch (ch) {case 'a': case 'A':case 'e': case 'E':case 'i': case 'I':case 'o': case 'O':case 'u': case 'U':
System.out.println("vowel“);break;
default: System.out.println("not a vowel“);
}
The break causes an exiting of the switch
Handles all of the other cases
Example – Simple calculations
System.out.print("Enter a number: ");int n1 = Integer.parseInt(stdin.readLine());
System.out.print("Enter another number: ");int n2 = Integer.parseInt(stdin.readLine());
System.out.print("Enter desired operator: ");char operator = stdin.readLine().charAt(0);
switch (operator) {case '+' : System.out.println(n1 + n2); break;case '-' : System.out.println(n1 - n2); break;case '*' : System.out.println(n1 * n2); break;case '/' : System.out.println(n1 / n2); break;default: System.out.println(“Illegal request“);
}
switch Statement Rules
The switch-expression must yield a value of char, byte, short, or int type and must always be enclosed in parentheses
The value1, ..., and valueN must have the same data type as the value of the switch-expression
The case statements are executed in sequential order
The keyword break is optional to use at the end of each case in order to terminate from the switch statement. But if the break statement is not present, the next case statement will be executed
Conditional Operator
(Boolean Expression) ? exp1 : exp2
Examples – Conditional Operator
if (x > 0) y = 1else y = -1;
is equivalent to
y = (x > 0) ? 1 : -1;
if (num % 2 == 0) System.out.println(num + “is
even”);else System.out.println(num + “is odd”);
is equivalent to
System.out.println( (num % 2 == 0)? num + “is even” : num + “is odd”);
Repetition Statements Looping: while, do-while and for
DO it if and only if condition is true DO it at least one before testing the condition DO it repeatedly until the counter is over
Nested loops
Using break and continue
while Loop Flow Chart
Expression
Action
true f alse
Expression isevaluated at the
start of eachiteration of the
loop
If Expression istrue, Action is
executed If Expression isfalse, program
executioncontinues withnext statement
Example – while Loop Flow Chart
int i = 0;
while (i < 100) { System.out.println( "Welcome to Java!"); i++;}
false
true
System.out.println("Welcoem to Java!"); i++;
Next Statement
(i < 100)
i = 0;
The do-while statement Syntax
do { Action
} while (Expression)
Semantics Execute Action
If Expression is true then execute Action again
Repeat this process until Expression evaluates to false
Action
true
false
Expression
The for Statement
Logical test expression that determines whether the action and update step areexecuted
for ( ForInit ; ForExpression ; ForUpdate ) Action
Update step is performed afterthe execution of the loop body
Initialization step prepares for thefirst evaluation of the test
expression
The body of the loop iterates wheneverthe test expression evaluates to true
The for Statement
int currentTerm = 1;
for (int i = 0; i < 5; ++i) {System.out.println(currentTerm);currentTerm *= 2;
}
The for Statement
int currentTerm = 1;
for (int i = 0; i < 5; ++i) {System.out.println(currentTerm);currentTerm *= 2;
}
Initialization stepis performed onlyonce -- just prior
to the firstevaluation of thetest expression
The for Statement
int currentTerm = 1;
for (int i = 0; i < 5; ++i) {System.out.println(currentTerm);currentTerm *= 2;
}
The body of the loop iterateswhile the test expression istrueInitialization step
is performed onlyonce -- just prior
to the firstevaluation of thetest expression
The for Statement
int currentTerm = 1;
for (int i = 0; i < 5; ++i) {System.out.println(currentTerm);currentTerm *= 2;
}
The body of the loop iterateswhile the test expression istrueInitialization step
is performed onlyonce -- just prior
to the firstevaluation of thetest expression
The body of the loop displays thecurrent term in the number series.It then determines what is to be thenew current number in the series
The for Statement
int currentTerm = 1;
for (int i = 0; i < 5; ++i) {System.out.println(currentTerm);currentTerm *= 2;
}
After each iteration of thebody of the loop, the updateexpression is reevaluated
The body of the loop iterateswhile the test expression istrueInitialization step
is performed onlyonce -- just prior
to the firstevaluation of thetest expression
The body of the loop displays thecurrent term in the number series.It then determines what is to be thenew current number in the series
For Expr
Act i on
true false
For I ni t
Post Expr
Evaluated onceat the beginning
of the forstatements's
executionThe ForExpr is
evaluated at thestart of each
iteration of theloop
If ForExpr is true,Action isexecuted
After the Actionhas completed,
thePostExpression
is evaluated
If ForExpr isfalse, program
executioncontinues withnext statement
After evaluating thePostExpression, the next
iteration of the loop starts
Nested loops
int m = 2;int n = 3;for (int i = 0; i < n; ++i) {
System.out.println("i is " + i);for (int j = 0; j < m; ++j) {
System.out.println(" j is " + j);}
}
Nested loops
int m = 2;int n = 3;for (int i = 0; i < n; ++i) {
System.out.println("i is " + i);for (int j = 0; j < m; ++j) {
System.out.println(" j is " + j);}
}i is 0 j is 0 j is 1i is 1 j is 0 j is 1i is 2 j is 0 j is 1
The break Keyword
The continue Keyword
break Statement vs. continue Statement
The break Statement It causes an immediate exit from the structures
of (while, for, do-while), then execution continues with the next statement
The continue Statement It skips the remaining statement in the body of
the structures of (while, for, do-while), and proceeds with the next iteration of the loop
Using break and continue
Discussion on: Example 3.5 : TestBreak.java
Testing a break Statement
Example 3.6 : TestContinue.java Testing a continue Statement
Summary
Control Statements
Selection Statements if, if…else, nested if switch conditional operator
Repetition Statements while, do…while, for nested loops break and continue