J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while...

26
JAVA PROGRAMMING 2 CH 03: CONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue F a l l . 2 0 1 4 1 J a v a P r o g r a m m i n g

Transcript of J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while...

Page 1: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

Java Program

ming

1

JAVA PROGRAMMING 2CH 03: CONTROL STATEMENTS if, for loop (review)

switch, while, do while

break, continue

Fall. 2014

Page 2: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

2

Java Program

ming

CONTENT

Condition construct: if [review] Condition construct: switch Iteration construct: for [review] Iteration construct: while and do-while Nested constructs Special control instructions: break and continue

Fall. 2014

Page 3: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

3

Java Program

ming

CATEGORIES OF FLOW CONTROL Sequential

Sequential is the flow type where instructions are executed one after another, from top to bottom.

Selection Selection is the flow type where one path out of a number of possibilities is

taken. Iteration

Iteration is the flow type where one or more instructions is executed repeatedly if certain conditions are fulfilled.

Transfer Transfer is the flow type where the point of execution jumps to a different

point in the program. Using transfer is considered as a poor programming style and makes the code

maintenance difficult. Java only supports the forward transfer, which transfer the execution point to

a point beyond the current execution point. Sometimes forward transfer makes the code less complex.

Fall. 2014

Page 4: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

4

Java Program

ming

if-CONSTRUCT Syntax form

if(<condition>) statementelse statement

if and else parts control a single statement. If more than one statement needed to be controlled, use code block.

The else part is optional. The else part must be associated with an if-part if it exists.

The condition expression must be a boolean expression. If the conditional expression is true, the target of the if will be

executed; otherwise, if it exists, the target of the else will be executed.

Fall. 2014

if( i > 0 ) a++; // this if statement is terminated here b++; // since the target of if statement is a single statement // if( i > 0 ) statement is terminated here else c++; // no if part to match, so it’s illegal

Page 5: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

5

Java Program

ming

FLOWCHART FOR if-CONSTRUCT

Fall. 2014

<condition>

Statement

true

Next statement

false

Statement

Page 6: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

6

Java Program

ming

NESTED if-CONSTRUCT

A nested if-construct is an if statement that is the target of another if or else.

An else statement always refers to the nearest if statement that is within the same block as the else and not already associated with an else.

Fall. 2014

Page 7: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

7

Java Program

ming

EXAMPLES OF NESTED IF-CONSTRUCT

Example 1

Example 2

Fall. 2014

if(i == 10) { if(j < 20) a = b; if(k > 100) c = d; else a = c; // this else refers to if(k > 100)}else a = d; // this else refers to if(i == 10)

if(i == 10) { if(j < 20) { a = b; if(k > 100) c = d; } else a = c; // this else refers to if(j<20)}else a = d; // this else refers to if(i == 10)

Java’s syntax is free of position!Using proper indentation makes

programs clearer!

Page 8: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

8

Java Program

ming

switch-CONSTRUCT

The switch-construct enables a program to select among several alternatives.

Syntax form

Fall. 2014

switch(<expression>) { case <constant1>: statement sequence break; case <constant2>: statement sequence break; case <constant3>: statement sequence break; … default: statement sequence}

Page 9: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

9

Java Program

ming

Executing switch-CONSTRUCT

Evaluating <expression> and comparing the result sequentially, from top to bottom, with constants following case-clauses.

When a match is found, the statements associated with that case are executed until the break is encountered or, in the case of default or the last case, until the end of the switch is reached.

The default statement sequence, if it exists, is executed if no case constant matches the expression. The default-clause is optional. If default-clause is not present, no action takes place if all

matches fail.

Fall. 2014

Page 10: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

10

Java Program

ming

SYNTAX RULES FOR switch-CONSTRUCT

Prior to JDK 7, the <expression> controlling the switch must be of type byte, short, int, char, or enum.

Beginning with JDK 7, <expression> can also be of type String.

Each value specified in the case clauses must be a unique constant expression. A constant expression is a expression which can be evaluated

during the compiling time. The type of each value specified in the case clauses must

be compatible with the type of <expression> .

Fall. 2014

Page 11: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

11

Java Program

ming

DEMO SEGMENT FOR switch-CONSTRUCT switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12 : System.out.println(“There are 31

days"); break; case 2: System.out.println(“There are 28 or

29 days"); break; case 4: case 6: case 9: case 11: System.out.println(“There are 30

days"); break; default: System.out.println("Invalid month."); }

Fall. 2014

Page 12: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

12

Java Program

ming

LOOPING

Java provides four types of looping (iteration) statements Traditional for while do-while Enhanced for

Supported after Java 2 version 1.5

All looping have 4 parts Initialization Iteration condition Body Termination condition

Fall. 2014

Page 13: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

TRADITIONAL for-CONSTRUCT

Fall. 2014

13

Java Program

ming

Syntax of while-statement for ( <init_exp> ; <test_exp> ; <post_exp> ) single-statement;

Test_ exp

statement

true

Next statement

false

init-_exp

post-_exp

Example

int sum = 0;

for(int count=0; count<=n; ++count ) {

sum += count;

} // count does not exist after this point

Page 14: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

14

Java Program

ming

MORE ON for-CONSTRUCT

The type of control variable can be any numeric types and char.

The loop control variable can be modified by any amount in <post-exp>.

It is a pre-condition looping. The <post-exp> is tested at the beginning of each loop. The code inside the loop may not be executed at all.

The <init-exp> and <post-exp> may consist of more than one expression separated by comma.

Fall. 2014

int i, j;for(i=0, j=i+10; i < j; i++, j--) System.out.println("i and j: " + i + " " + j);

Page 15: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

15

Java Program

ming

MORE ON for-CONSTRUCT

The <test-exp> must be a boolean expression. It does not need to involve the loop control variable.

All of the <init-exp> , <test-exp> and <post-exp> are option, but all three semicolons are not.

Missing <test-exp> means the result of <test-exp> is always true. The simplest for-construct for(;;); will perform nothing for

ever. When you declare a variable inside a for loop, the scope

of that variable ends when the for statement does.

Fall. 2014

for( int i = 0; i < 100; i++) sum += i;System.out.print(sum / i); // illegal since i is not declared

Page 16: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

16

Java Program

ming

while-CONSTRUCT

Fall. 2014 Syntax of while statement

while ( <condition> ) single-statement;

<condition>

statement

true

Next statement

false

Example

int sum = 0;int count = 0;while ( count <= n ) { sum += count; count++;}

The while statement is a pre-test looping.

Page 17: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

17

Java Program

ming

do-while-CONSTRUCT

Fall. 2014 Syntax of do-while statement

do single-statement; while ( <condition> );

<condition>

statement

true

Next statement

false

Example

int sum = 0;int count = 0;do { sum += count; count++;} while ( count <= n );

The do-while statement is a post-test looping.

Page 18: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

18

Java Program

ming

break STATEMENT

The break statement is used to force an immediate exit from a loop enclosing the statement, bypassing any remaining code in the body of the loop and the loop’s conditional test.

The break statement can be only used within a loop body or the body of switch-construct.

Fall. 2014

Page 19: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

19

Java Program

ming

DEMO PROGRAM FOR BREAK STATEMENT

// Using break with nested loops.class Break3 { public static void main(String args[]) { for(int i=0; i<3; i++) { System.out.println("Outer loop count: " + i);

System.out.print(" Inner loop count: ");

int t = 0; while(t < 100) { if(t == 10) break;//terminate while loop

if t is 10 System.out.print(t + " "); t++; } System.out.println(); } System.out.println("Loops complete."); }}

Fall. 2014

Page 20: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

20

Java Program

ming

break STATEMENT WITH LABEL The break statement with label can be used to terminate the execution

of a code block. The code block terminated by using a break statement with label does not

need to be the body of loop or switch. Syntax form for break statement with label

break <label>; A label is the identifier used to identify a code block or a statement. Syntax form for labeling code block

<label>: { <statement sequences> } When this form of break executes, control is transferred out of the

named code block or statement. The labeled code block or statement must enclose the break statement,

but it does not need to be the immediately enclosing block. This means that you can use a labeled break statement to exit from a set of

nested blocks.

Fall. 2014

Page 21: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

21

Java Program

ming

DEMO PROGRAM FOR break STATEMENT WITH LABEL // Using break with a label.class Break4 { public static void main(String args[]) { int i; for(i=1; i<4; i++) { one: { two: { three: { System.out.println("\ni is " + i); if(i==1) break one; if(i==2) break two; if(i==3) break three; System.out.println("won't print"); // this is never reached } System.out.println("After block three."); } System.out.println("After block two."); } System.out.println("After block one."); } System.out.println("After for."); }}

Fall. 2014

Page 22: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

22

Java Program

ming

TRY THIS …class Break6 { public static void main(String args[]) { int x=0, y=0; // here, put label before for statement. stop1: for(x=0; x < 5; x++) { for(y = 0; y < 5; y++) { if(y == 2) break stop1; // stop the for loop System.out.println("x and y: " + x + " " + y); } } System.out.println(); // now, put label immediately before { for(x=0; x < 5; x++){ stop2: { for(y = 0; y < 5; y++) { if(y == 2) break stop2; // stop the body of for, not for System.out.println("x and y: " + x + " " + y); } } } }}

Fall. 2014

Page 23: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

23

Java Program

ming

continue-CONSTRUCT

The continue statement forces the next iteration of the loop to take place, skipping any code between itself and the conditional expression that controls the loop.

In while and do-while loops, a continue statement will cause control to continues the loop by directly evaluating the <test-exp>.

In the case of the for, the <post-exp> of the loop is evaluated, then the loop continues by evaluating the <test-exp>.

Fall. 2014

Page 24: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

24

Java Program

ming

DEMO PROGRAM FOR continue-CONSTRUCT

// Use continue.

class ContDemo {

public static void main(String args[]) {

int i;

// print even numbers between 0 and 100

for(i = 0; i<=100; i++) {

if((i%2) != 0) continue;

// skipping the println and

// continuing the next loop

System.out.println(i);

}

}

}

Fall. 2014

The boolean expression is true for

odd number.

Page 25: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

25

Java Program

ming

continue STATEMENT WITH LABEL

The continue may specify a label to describe which enclosing loop to continue.

The statement labeled by a label used with continue statement must be a loop statement.

Fall. 2014

Page 26: J AVA P ROGRAMMING 2 C H 03: C ONTROL STATEMENTS if, for loop (review) switch, while, do while break, continue Fall. 2014 0 Java Programming.

26

Java Program

ming

DEMO PROGRAM FOR continue STATEMENT WITH LABEL

// Use continue with a label.

class ContToLabel {

public static void main(String args[]) {

outerloop:

for(int i=1; i < 10; i++) {

System.out.print("\nOuter loop pass " + i + ", Inner loop: ");

for(int j = 1; j < 10; j++) {

if(j == 5) continue outerloop;

// continue outer loop

System.out.print(j);

}

}

}

}

Fall. 2014