MELJUN CORTES Java Lecture Controls Structures

52
6 6 Control Control Structures Structures Java Fundamentals and Object- Java Fundamentals and Object- Oriented Programming Oriented Programming The Complete Java Boot Camp The Complete Java Boot Camp MELJUN CORTES MELJUN CORTES MELJUN CORTES MELJUN CORTES

description

MELJUN CORTES Java Lecture Controls Structures

Transcript of MELJUN CORTES Java Lecture Controls Structures

Page 1: MELJUN CORTES Java Lecture Controls Structures

66 Control Control StructuresStructures

Java Fundamentals and Object-Oriented Java Fundamentals and Object-Oriented ProgrammingProgramming

The Complete Java Boot CampThe Complete Java Boot Camp

MELJUN CORTESMELJUN CORTES

MELJUN CORTESMELJUN CORTES

Page 2: MELJUN CORTES Java Lecture Controls Structures

ObjectivesObjectives

At the end of the lesson, the student should be At the end of the lesson, the student should be able to:able to:

Use decision control structures (if, else, switch) Use decision control structures (if, else, switch) which allows selection of specific sections of which allows selection of specific sections of code to be executedcode to be executed

Use repetition control structures (while, do-Use repetition control structures (while, do-while, for) which allow executing specific while, for) which allow executing specific sections of code a number of timessections of code a number of times

Use branching statements (break, continue, Use branching statements (break, continue, return) which allows redirection of program flowreturn) which allows redirection of program flow

Page 3: MELJUN CORTES Java Lecture Controls Structures

Control StructuresControl Structures

Control structuresControl structures allows us to change the ordering of how the allows us to change the ordering of how the

statements in our programs are executedstatements in our programs are executed

Two types of Control StructuresTwo types of Control Structures decision control structuresdecision control structures

allows us to select specific sections of code to be executed

repetition control structuresrepetition control structures allows us to execute specific sections of the code a

number of times

Page 4: MELJUN CORTES Java Lecture Controls Structures

Decision Control StructuresDecision Control Structures

Decision control structuresDecision control structures Java statements that allows us to select and Java statements that allows us to select and

execute specific blocks of code while skipping execute specific blocks of code while skipping other sectionsother sections

Types:Types: if-statementif-statement if-else-statementif-else-statement If-else if-statementIf-else if-statement

Page 5: MELJUN CORTES Java Lecture Controls Structures

if-statementif-statement

if-statement if-statement specifies that a statement (or block of code) will be executed if and specifies that a statement (or block of code) will be executed if and

only if a certain boolean statement is true. only if a certain boolean statement is true.

if-statement has the form:if-statement has the form:if( boolean_expression )if( boolean_expression )

statement; statement; or or

if( boolean_expression ){ if( boolean_expression ){ statement1; statement1; statement2; statement2;

} } where, where,

boolean_expression is either a boolean expression or boolean variable.

Page 6: MELJUN CORTES Java Lecture Controls Structures

if-statement Flowchartif-statement Flowchart

Page 7: MELJUN CORTES Java Lecture Controls Structures

Example 1Example 1

int grade = 68; int grade = 68; if( grade > 60 ) if( grade > 60 )

System.out.println("Congratulations!System.out.println("Congratulations!"); ");

Page 8: MELJUN CORTES Java Lecture Controls Structures

Example 2Example 2

int grade = 68; int grade = 68; if( grade > 60 ){ if( grade > 60 ){ System.out.println("Congratulations!System.out.println("Congratulations!"); "); System.out.println("You passed!"); System.out.println("You passed!");

}}

Page 9: MELJUN CORTES Java Lecture Controls Structures

Coding GuidelinesCoding Guidelines

1. The 1. The boolean_expressionboolean_expression part of a statement part of a statement should evaluate to a boolean value. That should evaluate to a boolean value. That means that the execution of the condition means that the execution of the condition should either result to a value of true or a should either result to a value of true or a false. false.

2. Indent the statements inside the if-block.2. Indent the statements inside the if-block.

For example,For example,if( boolean_expression ){if( boolean_expression ){

//statement1; //statement1; //statement2; //statement2;

} }

Page 10: MELJUN CORTES Java Lecture Controls Structures

if-else statementif-else statement

if-else statementif-else statement used when we want to execute a certain statement if a condition is used when we want to execute a certain statement if a condition is

true, and a different statement if the condition is false.true, and a different statement if the condition is false.

if-else statement has the form:if-else statement has the form:if( boolean_expression ){ if( boolean_expression ){

statement1;statement1;statement2; statement2; . . . . . .

}}else{ else{

statement3;statement3;statement4; statement4; . . .. . .

}}

Page 11: MELJUN CORTES Java Lecture Controls Structures

FlowchartFlowchart

Page 12: MELJUN CORTES Java Lecture Controls Structures

Example 1Example 1

int grade = 68; int grade = 68;

if( grade > 60 ) if( grade > 60 ) System.out.println("Congratulations!System.out.println("Congratulations!"); ");

else else System.out.println("Sorry you System.out.println("Sorry you failed"); failed");

Page 13: MELJUN CORTES Java Lecture Controls Structures

Example 2Example 2

int grade = 68; int grade = 68;

if( grade > 60 ){ if( grade > 60 ){ System.out.println("Congratulations!System.out.println("Congratulations!");");System.out.println("You passed!"); System.out.println("You passed!");

} } else{ else{ System.out.println("Sorry you System.out.println("Sorry you failed"); failed");

} }

Page 14: MELJUN CORTES Java Lecture Controls Structures

Coding GuidelinesCoding Guidelines

1. To avoid confusion, always place the statement or 1. To avoid confusion, always place the statement or statements of an if or if-else block inside brackets {}. statements of an if or if-else block inside brackets {}.

2. You can have nested if-else blocks. This means that you 2. You can have nested if-else blocks. This means that you can have other if-else blocks inside another if-else block.can have other if-else blocks inside another if-else block.

For example, For example, if( boolean_expression ){ if( boolean_expression ){

if( boolean_expression ){if( boolean_expression ){ //some statements here //some statements here } }

} } else{ else{

//some statements here//some statements here}}

Page 15: MELJUN CORTES Java Lecture Controls Structures

if-else-else if statementif-else-else if statement

The statement in the else-clause of an if-else block The statement in the else-clause of an if-else block can be another if-else structures. can be another if-else structures.

This cascading of structures allows us to make more This cascading of structures allows us to make more complex selections. complex selections.

The statement has the form:The statement has the form:if( boolean_expression1 ) if( boolean_expression1 )

statement1; statement1; else if( boolean_expression2 ) else if( boolean_expression2 )

statement2; statement2; else else

statement3; statement3;

Page 16: MELJUN CORTES Java Lecture Controls Structures

FlowchartFlowchart

Page 17: MELJUN CORTES Java Lecture Controls Structures

ExampleExample

int grade = 68;

if( grade > 90 ){ System.out.println("Very good!");

} else if( grade > 60 ){

System.out.println("Very good!"); } else{

System.out.println("Sorry you failed"); }

Page 18: MELJUN CORTES Java Lecture Controls Structures

Common ErrorsCommon Errors

1. The condition inside the if-statement does not 1. The condition inside the if-statement does not evaluate to a boolean value. For example, evaluate to a boolean value. For example,

//WRONG //WRONG int number = 0; int number = 0; if( number ){ if( number ){

//some statements here //some statements here } }

The variable number does not hold a boolean value. The variable number does not hold a boolean value.

2. Writing 2. Writing elseifelseif instead of instead of else ifelse if..

Page 19: MELJUN CORTES Java Lecture Controls Structures

Common ErrorsCommon Errors

3. Using = instead of == for comparison. 3. Using = instead of == for comparison. For example, For example,

//WRONG //WRONG int number = 0; int number = 0; if( numberif( number = = 0 ){ 0 ){

//some statements here //some statements here } }

This should be written as, This should be written as, //CORRECT //CORRECT int number = 0; int number = 0; if( numberif( number == == 0 ){ 0 ){

//some statements here//some statements here} }

Page 20: MELJUN CORTES Java Lecture Controls Structures

Sample ProgramSample Program

1 public class Grade {2 public static void main( String[] args )3 {4 double grade = 92.0;5 if( grade >= 90 ){6 System.out.println( "Excellent!" );7 }8 else if( (grade < 90) && (grade >= 80)){9 System.out.println("Good job!" );10 }11 else if( (grade < 80) && (grade >= 60)){12 System.out.println("Study harder!" );13 }14 else{

System.out.println("Sorry, you failed.");15

16 }17 }18 }

Page 21: MELJUN CORTES Java Lecture Controls Structures

switch-statementswitch-statement

switchswitch allows branching on multiple outcomes. allows branching on multiple outcomes.

switch statement has the form:switch statement has the form:switch( switch_expression ){ switch( switch_expression ){

case case_selector1: case case_selector1: statement1;// statement1;// statement2;//block 1 statement2;//block 1 break; break;

case case_selector2: case case_selector2: statement1;// statement1;// statement2;//block 2 statement2;//block 2 break; break;

::default: default:

statement1;//statement1;// statement2;//block n statement2;//block n

} }

Page 22: MELJUN CORTES Java Lecture Controls Structures

switch-statementswitch-statement

where,where, switch_expression switch_expression

is an integer or character expression case_selector1, case_selector2 and so on, case_selector1, case_selector2 and so on,

are unique integer or character constants.

Page 23: MELJUN CORTES Java Lecture Controls Structures

switch-statementswitch-statement

When a switch is encountered, When a switch is encountered, Java first evaluates the switch_expression, and Java first evaluates the switch_expression, and

jumps to the case whose selector matches the jumps to the case whose selector matches the value of the expression. value of the expression.

The program executes the statements in order The program executes the statements in order from that point on until a break statement is from that point on until a break statement is encountered, skipping then to the first encountered, skipping then to the first statement after the end of the switch structure. statement after the end of the switch structure.

If none of the cases are satisfied, the default If none of the cases are satisfied, the default block is executed. Take note however, that the block is executed. Take note however, that the default part is optional. default part is optional.

Page 24: MELJUN CORTES Java Lecture Controls Structures

switch-statementswitch-statement

NOTE:NOTE: Unlike with the if statement, the multiple Unlike with the if statement, the multiple

statements are executed in the switch statement statements are executed in the switch statement without needing the curly braces. without needing the curly braces.

When a case in a switch statement has been When a case in a switch statement has been matched, all the statements associated with that matched, all the statements associated with that case are executed. Not only that, the statements case are executed. Not only that, the statements associated with the succeeding cases are also associated with the succeeding cases are also executed. executed.

To prevent the program from executing statements To prevent the program from executing statements in the subsequent cases, we use a break in the subsequent cases, we use a break statement as our last statement. statement as our last statement.

Page 25: MELJUN CORTES Java Lecture Controls Structures

FlowchartFlowchart

Page 26: MELJUN CORTES Java Lecture Controls Structures

ExampleExample1 public class Grade {2 public static void main( String[] args )3 {4 int grade = 92;5 switch(grade){6 case 100:7 System.out.println( "Excellent!" );8 break;9 case 90:10 System.out.println("Good job!" ); 11 break; 12 case 80:13 System.out.println("Study harder!" );14 break;15 default:16 System.out.println("Sorry, you failed.");17 }18 } 19 }

Page 27: MELJUN CORTES Java Lecture Controls Structures

Coding GuidelinesCoding Guidelines

1. Deciding whether to use an if statement or a 1. Deciding whether to use an if statement or a switch statement is a judgment call. You can switch statement is a judgment call. You can decide which to use, based on readability decide which to use, based on readability and other factors.and other factors.

2. An if statement can be used to make 2. An if statement can be used to make decisions based on ranges of values or decisions based on ranges of values or conditions, whereas a switch statement can conditions, whereas a switch statement can make decisions based only on a single make decisions based only on a single integer or character value. Also, the value integer or character value. Also, the value provided to each case statement must be provided to each case statement must be unique. unique.

Page 28: MELJUN CORTES Java Lecture Controls Structures

Repetition Control StructuresRepetition Control Structures

Repetition control structures Repetition control structures are Java statements that allows us to execute are Java statements that allows us to execute

specific blocks of code a number of times. specific blocks of code a number of times.

Types:Types: while-loop while-loop do-while loopdo-while loop for-loopfor-loop

Page 29: MELJUN CORTES Java Lecture Controls Structures

while-loopwhile-loop

while loopwhile loop is a statement or block of statements that is repeated as long is a statement or block of statements that is repeated as long

as some condition is satisfied. as some condition is satisfied.

while loop has the form:while loop has the form:while( boolean_expression ){ while( boolean_expression ){

statement1; statement1; statement2; statement2; . . . . . .

} }

The statements inside the while loop are executed as long as The statements inside the while loop are executed as long as the boolean_expression evaluates to true. the boolean_expression evaluates to true.

Page 30: MELJUN CORTES Java Lecture Controls Structures

Example 1Example 1

int x = 0;

while (x<10) { System.out.println(x); x++;}

Page 31: MELJUN CORTES Java Lecture Controls Structures

Example 2Example 2

//infinite loop while(true)

System.out.println(“hello”);

Page 32: MELJUN CORTES Java Lecture Controls Structures

Example 3Example 3

//no loops // statement is not even executed while (false)

System.out.println(“hello”);

Page 33: MELJUN CORTES Java Lecture Controls Structures

do-while-loopdo-while-loop

do-while loopdo-while loop is similar to the while-loopis similar to the while-loop statements inside a do-while loop are executed several times as statements inside a do-while loop are executed several times as

long as the condition is satisfiedlong as the condition is satisfied The main difference between a while and do-while loop:The main difference between a while and do-while loop:

the statements inside a do-while loop are executed at least once.

do-while loop has the form:do-while loop has the form:do{ do{

statement1; statement1; statement2; statement2; . . . . . .

}while( boolean_expression );}while( boolean_expression );

Page 34: MELJUN CORTES Java Lecture Controls Structures

Example 1Example 1

int x = 0;

do { System.out.println(x); x++;

}while (x<10);

Page 35: MELJUN CORTES Java Lecture Controls Structures

Example 2Example 2

//infinite loop do{

System.out.println(“hello”); } while (true);

Page 36: MELJUN CORTES Java Lecture Controls Structures

Example 3Example 3

//one loop // statement is executed once do

System.out.println(“hello”); while (false);

Page 37: MELJUN CORTES Java Lecture Controls Structures

Coding GuidelinesCoding Guidelines

1. Common programming mistakes when using the do-1. Common programming mistakes when using the do-while loop is forgetting to write the semi-colon after while loop is forgetting to write the semi-colon after the while expression. the while expression. do{ do{

...... }while(boolean_expression)//WRONG->forgot }while(boolean_expression)//WRONG->forgot semicolon;semicolon;

2. Just like in while loops, make sure that your do-while 2. Just like in while loops, make sure that your do-while loops will terminate at some pointloops will terminate at some point

Page 38: MELJUN CORTES Java Lecture Controls Structures

for-loopfor-loop

for loopfor loop allows execution of the same code a number of times. allows execution of the same code a number of times.

for loop has the form:for loop has the form:for(InitializationExpression;LoopCondition;StepExpresfor(InitializationExpression;LoopCondition;StepExpression)sion){ {

statement1; statement1; statement2; statement2; . . . . . .

} } where, where,

InitializationExpression -initializes the loop variable. LoopCondition - compares the loop variable to some limit value. StepExpression - updates the loop variable.

Page 39: MELJUN CORTES Java Lecture Controls Structures

ExampleExample

The code shown above is equivalent to the The code shown above is equivalent to the following while loop.following while loop.

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

System.out.println(i); }

int i = 0; while( i < 10 ){

System.out.print(i); i++;

}

Page 40: MELJUN CORTES Java Lecture Controls Structures

Branching StatementsBranching Statements

Branching statements allows us to redirect Branching statements allows us to redirect the flow of program execution. the flow of program execution.

Java offers three branching statements:Java offers three branching statements: breakbreak continuecontinue return.return.

Page 41: MELJUN CORTES Java Lecture Controls Structures

Unlabeled break statementUnlabeled break statement

unlabeled breakunlabeled break terminates the enclosing switch statement, and terminates the enclosing switch statement, and

flow of control transfers to the statement flow of control transfers to the statement immediately following the switch. immediately following the switch.

This can also be used to terminate a for, while, This can also be used to terminate a for, while, or do-while loopor do-while loop

Page 42: MELJUN CORTES Java Lecture Controls Structures

ExampleExample

String String names[]={"Beah","Bianca","Lance","Belle","Nico","Yza","Gem","names[]={"Beah","Bianca","Lance","Belle","Nico","Yza","Gem","Ethan"};Ethan"};

String String searchName = "Yza";searchName = "Yza";booleanboolean foundName = false;foundName = false;

for( int i=0; i< names.length; i++ ){for( int i=0; i< names.length; i++ ){if( names[i].equals( searchName )){if( names[i].equals( searchName )){

foundName = true;break;

}}}}if( foundName )if( foundName ) System.out.println( searchName + " found!" );System.out.println( searchName + " found!" );elseelse System.out.println( searchName + " not System.out.println( searchName + " not

found." );found." );

Page 43: MELJUN CORTES Java Lecture Controls Structures

labeled break statementlabeled break statement

labeled break statementlabeled break statement terminates an outer statement, which is identified by terminates an outer statement, which is identified by

the label specified in the break statement. the label specified in the break statement. the flow of control transfers to the statement the flow of control transfers to the statement

immediately following the labeled (terminated) immediately following the labeled (terminated) statement.statement.

The sample program in the next slide searches for a The sample program in the next slide searches for a value in a two-dimensional array. Two nested for value in a two-dimensional array. Two nested for loops traverse the array. When the value is found, a loops traverse the array. When the value is found, a labeled break terminates the statement labeled labeled break terminates the statement labeled search, which is the outer for loop.search, which is the outer for loop.

Page 44: MELJUN CORTES Java Lecture Controls Structures

ExampleExample

int[][] numbers = {{1, 2, 3},int[][] numbers = {{1, 2, 3}, {4, 5, 6},{7, 8, 9}};{4, 5, 6},{7, 8, 9}};int searchNum = 5;int searchNum = 5;boolean foundNum = false;boolean foundNum = false;

searchLabel:searchLabel:for( int i=0; i<numbers.length; i++ ){for( int i=0; i<numbers.length; i++ ){

for( int j=0; j<numbers[i].length; j++ ){for( int j=0; j<numbers[i].length; j++ ){if( searchNum == numbers[i][j] ){

foundNum = true;break searchLabel;

}}}

}}if( foundNum )if( foundNum )System.out.println(searchNum + " found!" );System.out.println(searchNum + " found!" );elseelse System.out.println(searchNum + " not System.out.println(searchNum + " not

found!");found!");

Page 45: MELJUN CORTES Java Lecture Controls Structures

Unlabeled continue statementUnlabeled continue statement

unlabeled continue statementunlabeled continue statement skips to the end of the innermost loop's body skips to the end of the innermost loop's body

and evaluates the boolean expression that and evaluates the boolean expression that controls the loop, basically skipping the controls the loop, basically skipping the remainder of this iteration of the loop. remainder of this iteration of the loop.

Page 46: MELJUN CORTES Java Lecture Controls Structures

ExampleExampleString names[] = {"Beah", "Bianca", "Lance", String names[] = {"Beah", "Bianca", "Lance",

"Beah"};"Beah"};intint count = 0;count = 0;

for( int i=0; i<names.length; i++ ){for( int i=0; i<names.length; i++ ){

if( !names[i].equals("Beah") ){if( !names[i].equals("Beah") ){

continue; //skip next statement}}count++;count++;

}}System.out.println("There are "+count+" Beahs in System.out.println("There are "+count+" Beahs in

the list");the list");

Page 47: MELJUN CORTES Java Lecture Controls Structures

Labeled continue statementLabeled continue statement

labeled continue statementlabeled continue statement skips the current iteration of an outer loop skips the current iteration of an outer loop

marked with the given label.marked with the given label.

Page 48: MELJUN CORTES Java Lecture Controls Structures

ExampleExampleouterLoop:outerLoop:for( int i=0; i<5; i++ ){for( int i=0; i<5; i++ ){

for( int j=0; j<5; j++ ){for( int j=0; j<5; j++ ){

System.out.println("Inside for(j) loop"); //message1

if( j == 2 ) continue outerLoop;}}System.out.println("Inside for(i) System.out.println("Inside for(i) loop"); //message2loop"); //message2

}} In this example, message 2 never gets printed since we have In this example, message 2 never gets printed since we have

the statement continue outerloop which skips the iteration.the statement continue outerloop which skips the iteration.

Page 49: MELJUN CORTES Java Lecture Controls Structures

return statementreturn statement

return statementreturn statement used to exit from the current method. used to exit from the current method. flow of control returns to the statement that flow of control returns to the statement that

follows the original method call. follows the original method call.

Page 50: MELJUN CORTES Java Lecture Controls Structures

return statementreturn statement

To return a valueTo return a value simply put the value (or an expression that simply put the value (or an expression that

calculates the value) after the return keyword. calculates the value) after the return keyword. For example,For example,

return ++count;

orreturn "Hello";

The data type of the value returned by return The data type of the value returned by return must match the type of the method's declared must match the type of the method's declared return value. return value.

Page 51: MELJUN CORTES Java Lecture Controls Structures

return statementreturn statement

When a method is declared void, use the When a method is declared void, use the form of return that doesn't return a value. form of return that doesn't return a value. For example,For example,

return;

We will cover more about return statements We will cover more about return statements later when we discuss about methods.later when we discuss about methods.

Page 52: MELJUN CORTES Java Lecture Controls Structures

SummarySummary Decision Control StructuresDecision Control Structures

ifif if-elseif-else if – else ifif – else if switchswitch

Repetition Control StructuresRepetition Control Structures whilewhile do-whiledo-while forfor

Branching StatementsBranching Statements breakbreak continuecontinue returnreturn