Vous êtes sur la page 1sur 69

ITM1 Arts & Style in Programming

Control Flow Statements

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

Use decision control structures (if, else, switch) which allows selection of specific sections of code to be executed Use repetition control structures (while, do-while, for) which allow executing specific sections of code a number of times Use branching statements (break, continue, return) which allows redirection of program flow

Control Flow Statements


Control flow statements determine the order in which other statements are executed. Java language supports several control flow statements, including:
Control Structure Decision Repetition Exception Branching Keyword If-else, switch-case For , while, do-while Try-catch-finally, throw Break, continue, label: , return

Decision Control Structure: The if-else statement


Java's if-else statement provides your programs with the ability to selectively execute other statements based on some criteria. This is the simplest version of the if statement: the statement governed by the if is executed if some condition is true. Generally, the simple form of if can be written like this:
if (boolean expression) statement to do if expression is true;

What if you wanted to perform a different set of statements if the expression is false? Well, you can use the else statement for that.
4

Coding Guidelines
1. The boolean_expression part of a statement should evaluate to a boolean value. 2. That means that the execution of the condition should either result to a value of true or a false. 3. Indent the statements inside the if-block. For example, if( boolean_expression ){ //statement1; //statement2; }
5

The if-else statement


if (expression) statement to do if expression is true; else statement to do if expression is false;

What if you intend to do more than one statements if the expression is true? What about if you intend to do more than one statements if the expression is false? Well just place them in a block using the open brace as the start and ending it with a close brace.
if (expression) { statement1 to do if expression is true; statement2 to do if expression is true; statementN to do if expression is true; }
6

The if-else statement


if (expression) { statement1 statement2 statementN } else { statement1 statement2 statementN }

to do if expression is true; to do if expression is true; to do if expression is true;

to do if expression is false; to do if expression is false; to do if expression is false;

The if-else statement: Code Snippet


int grade = 68; if( grade > 60 ) System.out.println("Congratulations!"); else System.out.println("Sorry you failed");

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

Flowchart of if-else statement

Coding Guidelines
1. To avoid confusion, always place the statement or statements of an if or if-else block inside brackets {}. 1. You can have nested if-else blocks. This means that you can have other if-else blocks inside another if-else block. For example,

if( boolean_expression ){ if( boolean_expression ){ . . . } } else{ . . . }

10

If-Else-If Statement
The statement in the else-clause of an if-else block can be another ifelse structures. This cascading of structures allows us to make more complex selections.

if( boolean_expression1 ) statement1; else if( boolean_expression2 ) statement2; else statement3;

11

Flowchart for If-Else-If Statement

12

If-Else-If Statement: Code Snippet

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"); }

13

Common Errors when using the if-else statements:


1. The condition inside the if-statement does not evaluate to a boolean value. For example, The variable number does not hold a Boolean value.
//WRONG int number = 0; if( number ){ //some statements here }

2. Using = instead of == for comparison. For example, //WRONG int number = 0; if( number = 0 ){ //some statements here } This should be written as, //CORRECT int number = 0; if( number ==0 ){ //some statements here } 3. Writing elseif instead of else if.
14

Example for if-else-else if


public class Grade { public static void main( String[] args ) { double grade = 92.0; if( grade >= 90 ){ System.out.println( "Excellent!" ); } else if( (grade < 90) && (grade >= 80)){ System.out.println("Good job!" ); } else if( (grade < 80) && (grade >= 60)){ System.out.println("Study harder!" ); } else{ System.out.println("Sorry, you failed."); } } }
15

Nested-If Statement
int testscore; char grade; if (testscore >= 90) { grade = 'A'; } else if (testscore >= 80) { grade = 'B'; } else if (testscore >= 70) { grade = 'C'; } else if (testscore >= 60) { grade = 'D'; } else { grade = 'F'; }
16

The switch Statement


Another way to indicate a branch is through the switch keyword. The switch construct allows branching on multiple outcomes.
switch( switch_expression ){ case case_selector1: statement1; // statement2; //block 1 . . . // break; case case_selector2: statement1; // statement2; //block 2 . . . // break; . . . default: statement1; // statement2; //block n . . . // break; }

switch_expression is an integer or character expression case_selector1, case_selector2 and so on, are unique integer or character constants.

17

Flowchart: The switch Statement

18

Notes
Unlike with the if statement, the multiple statements are executed in the switch statement without needing the curly braces. When a case in a switch statement has been matched, all the statements associated with that case are executed. Not only that, the statements associated with the succeeding cases are also executed. To prevent the program from executing statements in the subsequent cases, we use a break statement as our last statement.

19

Example of Switch
public class Grade { public static void main( String[] args ){ int grade = 92; switch(grade){ case 100: System.out.println( "Excellent!" ); break; case 90: System.out.println("Good job!" ); break; case 80: System.out.println("Study harder!" ); break; default: System.out.println("Sorry, you failed."); } } }
20

The switch Statement


Use the switch statement to conditionally perform statements based on some expression. For example, suppose that your program contained an integer named month whose value indicated the month in some date. Suppose also that you wanted to display the name of the month based on its integer equivalent
int month; . . . switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break; }

21

The switch Statement


The switch statement evaluates its expression, in this case, the value of month, and executes the appropriate case statement. Of course, you could implement this as an if statement:
int month; . . . if (month == 1) { System.out.println("January"); } else if (month == 2) { System.out.println("February"); . . . // you get the idea . . .

22

Coding Guidelines
Deciding whether to use an if statement or a switch statement is a judgment call. You can decide which to use based on readability and other factors. An if statement can be used to make decisions based on ranges of values or conditions, whereas a switch statement can make decisions based only on a single integer or character value. Also, the value provided to each case statement must be unique Each case statement must be unique and the value provided to each case statement must be of the same data type as the data type returned by the expression provided to the switch statement. The break statements in a case statement causes control to break out of the switch and continue with the first statement following the switch. The break statements are necessary because case statements fall through. That is, without an explicit break control will flow sequentially through subsequent case statements.
23

Like in the following Java code that computes the number of days in a month according to the old rhyme that starts "Thirty days hath September April, June and November all the rest is Thirthy-one except February..":
int month; int numDays; . . . switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numDays = 31; break; case 4: case 6: case 9: case 11: numDays = 30; break; case 2: if (((year%4==0) && !(year % 100 == 0))||(year % 400 == 0) ) numDays = 29; else numDays = 28; break; } 24

You can use the default statement at the end of the switch to handle all values that aren't explicitly handled by one of the case statements.
int month; . . . switch (month) { case 1: System.out.println("January"); break; case 2: System.out.println("February"); break; case 3: System.out.println("March"); break; case 4: System.out.println("April"); break; case 5: System.out.println("May"); break; case 6: System.out.println("June"); break; case 7: System.out.println("July"); break; case 8: System.out.println("August"); break; case 9: System.out.println("September"); break; case 10: System.out.println("October"); break; case 11: System.out.println("November"); break; case 12: System.out.println("December"); break;

default: System.out.println("Hey, that's not a valid month!"); break;


}
25

Repetition Control Structure


Repetition control structures are Java statements that allows us to execute specific blocks of code a number of times. There are three types of repetition control structures, the while, do-while and for loops.

26

The While Loop


while loop is a statement or block of statements that is repeated as long as some condition is satisfied.
while (expression) { statement to do while expression becomes is true; }

The statements inside the while loop are executed as long as the boolean_expression evaluates to true.
int i = 4; while ( i > 0 ){ System.out.print(i); i--; }

The sample code shown will print 4321 on the screen. Take note that if the line containing the statement i--; is removed, this will result to an infinite loop, or a loop that does not terminate. Therefore, when using while loops or any kind of repetition control structures, make sure that you add some statements that will allow your loop to terminate at some point.
27

Examples of While Loop


int x = 0; while (x<10) { System.out.println(x); x++; } //infinite loop while(true) System.out.println(hello);

//no loops // statement is not even executed while (false) System.out.println(hello);

28

The Do-While Loop


The do-while loop is similar to the while-loop. The statements inside a do-while loop are executed several times as long as the condition is satisfied. The main difference between a while and do-while loop is that, the statements inside a do-while

loop are executed at least once.


do{ statement1; statement2; . . . }while( boolean_expression );

The statements inside the do-while loop are first executed, and then the
condition in the boolean_expression part is evaluated. If this evaluates to true, the statements inside the do-while loop are executed again

29

Code Snippets for Do-While Loop


int x = 0; do { System.out.println(x); x++; }while (x<10); //infinite loop do{ System.out.println(hello); } while (true); //one loop // statement is executed once do System.out.println(hello); while (false); Output: 0123456789 on the screen.

This example will result to an infinite loop, that prints hello on screen.

Output: hello on the screen.

30

Coding Guidelines
1. Common programming mistakes when using the do-while loop is forgetting to write the semi-colon after the while expression.
do{ ... }while(boolean_expression) //WRONG->forgot semicolon ; 2. Just like in while loops, make sure that your do-while loops will terminate at some point.

31

The for Loop


The for loop, like the previous loops, allows execution of the same code a number of times. The for loop has the form,
for (InitializationExpression; LoopCondition; StepExpression){ statement1; statement2; . . . }

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

32

Example of for Loop


int i; for( i = 0; i < 10; i++ ){ System.out.print(i); }
the statement i=0, first initializes the variable. the condition expression i<10 is evaluated. If this evaluates to true, then the statement inside the for loop is executed. the expression i++ is executed, and then the condition expression is again evaluated. This goes on and on, until the condition expression evaluates to false.

33

Example of for Loop


The for loop example is equivalent to the while loop shown below

int i = 0; while( i < 10 ){ System.out.print(i); i++; }

34

Nested Loops
Just as if statements can be nested, so can loops. You can place a while loop within a while loop or a for loop within a for loop. In short, when we say nested loop, we have a loop within a loop Example : Create a program that displays numbers from 1-5 in this manner

1 12 123
and so on then printing it manually is not recommended since you can accomplish it using a single print method to print the number no matter how deep the number goes.

35

Nested Loops
int x,y; for (x=1; x<=3;x++) { //outer loop for(y=1;y<=x;y++) // inner loop System.out.print(y); System.out.println(); /*forces the cursor to move to the next row when the inner loop is completed */ } Analysis: The outer loop is executed first with x having an initial value of 1. It then performs the next loop where another variable is initialized to 1. This loop will terminate if the value of y is greater than x. At this point, the statement inside the inner loop will only execute once since the value of x is only 1 therefore printing the value of y which is also 1. The cursor does not go down the next line. There is no {} that covers the two print methods therefore the second println statement will be executed once the inner loops condition is satisfied. The outer loops value will only increment once the inner loops condition is satisfied or completed.
36

Nested Loops
Value of x 1 2 Value of y 1 1 2 1 2 3

Therefore if you want to increase the number being produced by the loop, change the value of x in the outer loop (changing it to 4 would display the output below). 1 12 123 1234 Puzzle: How would you generate this output? 1 22 333 *** you do not have to reconstruct your loop. You only have to change 1 value from the loop.
37

Some variations on the for loop


// Use commas in a for statement. int i, j;

for(i=0, j=10; i < j; i++, j--)


System.out.println("i and j: " + i + " " + j); } } The output from the program is shown here: i and j: 0 10 i and j: 1 9 i and j: 2 8 i and j: 3 7 i and j: 4 6

38

Some variations on the for loop


Some interesting for loop variations are created by leaving pieces of the loop definition empty. In Java, it is possible for any or all of the initialization, condition, or iteration portions of the for loop to be blank The output from the program is shown here: int i; Pass #0 for(i = 0; i < 10; ) { Pass #1 System.out.println("Pass #" + i); Pass #2 i++; // increment loop control var Pass #3 } Pass #4 } Pass #5 Pass #6 Pass #7 Pass #8 Pass #9

39

Some variations on the for loop


the initialization portion is also moved out of the for.

int i;

i = 0; // move initialization out of loop


for(; i < 10; ) { System.out.println("Pass #" + i); i++; // increment loop control var }

In this version,i is initialized before the loop begins, rather than as part of thefor. Normally, you will want to initialize the loop control variable inside the for. Placing the initialization outside of the loop is generally done only when the initial value is derived through a complex process that does not lend itself to containment inside the for statement.

40

Branching Statements
Branching statements allows us to redirect the flow of program execution. Java offers three branching statements: break, continue and return.

41

break statement
The break statement has two forms: unlabeled (we saw its unlabeled form in the switch statement) and labeled.

Unlabeled break statement


The unlabeled break terminates the enclosing switch statement, and flow of control transfers to the statement immediately following the switch. You can also use the unlabeled form of the break statement to terminate a for, while, or do-while loop.

42

break statement example


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

string searchName = "Yza"; boolean foundName = false;


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

break;
} } if( foundName ){ System.out.println( searchName + " found!" ); } else{ System.out.println( searchName + " not found." ); } In this example, if the search string "Yza" is found, the for loop will stop 43 and flow of control transfers to the statement following the for loop.

break statement
Labeled break statement
The labeled form of a break statement terminates an outer

statement, which is identified by the label specified in the break statement. The following program searches for a value in a
two-dimensional array. Two nested for loops traverse the array. When the value is found, a labeled break terminates the statement labeled search, which is the outer for loop.

44

Example of labeled break statement


int[][] numbers = {{1, 2, 3}, {4, 5, 6},{7, 8, 9}}; int searchNum = 5; boolean foundNum = false; searchLabel: for( int i=0; i<numbers.length; i++ ){ for( int j=0; j<numbers[i].length; j++ ){ if( searchNum == numbers[i][j] ){ foundNum = true; break searchLabel; } } } if( foundNum ){ System.out.println( searchNum + " found!" ); } else{ System.out.println( searchNum + " not found!" ); }
The break statement terminates the labeled statement; it does not transfer the flow of control to the label. The flow of control transfers to the statement immediately following the labeled 45 (terminated) statement.

Another example of break statement


int x; for(x=0; x<100; x++) { System.out.println(x); if ( x == 10) break; } This prints the numbers 0 through 10 on the screen and then terminates because the break causes immediate exit form the loop, overriding the conditional test x<100 built into the loop.

46

Sample Break that uses JOptionPane


import javax.swing.JOptionPane; public class SampleBreak { public static void main(String[] args) { String anyInt; int intValue; do { anyInt = JOptionPane.showInputDialog("Please input an integer" ); intValue = Integer.parseInt(anyInt); if (intValue < 0){ JOptionPane.showMessageDialog(null, "You entered a negative number. Program will terminate!", "Sample Output", JOptionPane.INFORMATION_MESSAGE);break; } if (intValue != 0){JOptionPane.showMessageDialog(null, "You entered a non-zero number!","Sample Output", JOptionPane.INFORMATION_MESSAGE);} else {JOptionPane.showMessageDialog(null, "You entered a zero number!", "Sample Output", JOptionPane.INFORMATION_MESSAGE);} } while (intValue !=0); } }
47

continue statement
The continue statement has two forms: unlabeled and labeled. You can use the continue statement to skip the current iteration of a for, while or do-while loop. The continue construct can be used to short-circuit parts of a for, do or while loop. When a continue statement is encountered, execution of the current loop immediately resume at the top, skipping all other code between it and the end of the loop.

Unlabeled continue statement


The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop, basically skipping the remainder of this iteration of the loop.
48

unlabeled continue statement


The following example counts the number of "Beah"s in the array.
String names[] = {"Beah", "Bianca", "Lance","Beah"};
int count = 0; for( int i=0; i<names.length; i++ ){ if( !names[i].equals("Beah") ){

continue;
} count++; }

//skip next statement

System.out.println("There are " + count + " Beahs in the list");


49

labeled continue statement


The labeled form of the continue statement skips iteration of an outer loop marked with the given label. the current

outerLoop:
for(int i=0; i<5; i++){ 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) loop"); //message2 } }

In this example, message 2 never gets printed since we have the statement continue outerloop which skips the iteration.
50

Sample Continue that uses JOptionPane


import javax.swing.JOptionPane; public class SampleContinue { public static void main(String[] args) { String anyInt; int intSum = 0, intValue; for (int intCtr=0; intCtr <=3; intCtr++){ anyInt = JOptionPane.showInputDialog("Please input no."+ intCtr); intValue = Integer.parseInt(anyInt); if (intValue <0){ JOptionPane.showMessageDialog(null, "You entered a negative number!", "Sample Output", JOptionPane.ERROR_MESSAGE);

continue;
} intSum += intValue; } JOptionPane.showMessageDialog(null, "Sum of the integers = " + intSum, "Sample Output", JOptionPane.INFORMATION_MESSAGE); } }
51

return statement
The return statement is used to exit from the current method. The flow of control returns to the statement that follows the original method call. The return statement has two forms: one that returns a value and one that doesn't. To return a value, simply put the value (or an expression that calculates the value) after the return keyword. For example,
return ++count;
or return "Hello";

The data type of the value returned by return must match the type of the method's declared return value. When a method is declared void, use the form of return that doesn't return a value. For example,
return;

52

SampleWhileLoop that uses JOptionPane


package lesson3_Java_Loops_Strings; import javax.swing.JOptionPane; public class SampleWhileLoop { public static void main(String[] args) { String anyInt; int intValue=100; while (intValue!=0){ anyInt=JOptionPane.showInputDialog("Please input an integer "); intValue=Integer.parseInt(anyInt); // name of package

if (intValue !=0){ JOptionPane.showMessageDialog(null, "You entered a non-zero value!", "Sample Output", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Now you entered a zero!", "Sample Output", JOptionPane.INFORMATION_MESSAGE); }
} } }
53

SampleDoWhileLoop that uses JOptionPane


package lesson3_Java_Loops_Strings; import javax.swing.JOptionPane; public class SampleDoWhileLoop { public static void main(String[] args) { String anyInt; int intValue; do { anyInt = JOptionPane.showInputDialog("Please enter a value "); intValue = Integer.parseInt(anyInt); if (intValue !=0) { JOptionPane.showMessageDialog(null, "You entered a non-zero value!", "Sample Output", JOptionPane.INFORMATION_MESSAGE); } else { JOptionPane.showMessageDialog(null, "Now you entered a zero value!", "Sample Output", JOptionPane.INFORMATION_MESSAGE);} } while (intValue !=0);} } }
54

// name of package

SampleForLoop that uses JOptionPane


package lesson3_Java_Loops_Strings; import javax.swing.JOptionPane; public class SampleForLoop { public static void main(String[] args) { String anyInt; int intSum=0, intValue; for (int intCtr=1; intCtr <=3; intCtr++){ anyInt = JOptionPane.showInputDialog("Please input integer no. " + intCtr); intValue = Integer.parseInt(anyInt); intSum += intValue; } JOptionPane.showMessageDialog(null,"Sum of the integers = " + intSum, "Sample Output", JOptionPane.INFORMATION_MESSAGE); // name of package

}
}
55

Exception Handling

56

What are exceptions?


Exceptions are short for exceptional events. These are simply errors that occur during runtime, causing the normal program flow to be disrupted. There are different type of errors that can occur. Examples: divide by zero errors, accessing the elements of an array beyond its range, invalid input, hard disk crash, opening a non-existent file and heap memory exhausted.

57

The Error and Exception Classes


Throwable all exceptions are derived form this class. Two general categories of exceptions

1. Error Class. is used by the Java run-time system to handle errors occurring in
the run-time environment. These are generally beyond the control of user programs since these are caused by the run-time environment. Examples include out of memory errors and hard disk crash. 2. Exception Class. refer to conditions that user programs can reasonably deal with. These are usually the result of some flaws in the user program code. Example of Exceptions are the division by zero error and the array out-of-bounds error.

58

An Example

Running the code would display the following error message.

59

Catching Exceptions
The try-catch Statements
The keywords try, catch and finally are used to handle different types of exceptions. These three keywords are used together but the finally block is optional General syntax for writing a try-catch statement: try { <code to be monitored for exceptions> } catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs> } ... } catch (<ExceptionTypeN> <ObjName>) { <handler if ExceptionTypeN occurs> } The catch block starts after the close curly brace of the preceding try or catch block. Statements within the block are indented.

60

Applying this to DivByZero program


The divide by zero error is an example of an ArithmeticException. Thus, the exception type indicated in the catch clause is this class. The program handles the error by simply printing out the description of the problem.

61

An example of a code that handles more than one type of exception


//line 4 throw ArrayIndexOutOfBoundsExc eption when the user forgets to input an argument //line 5 throws an ArithmeticException if the user enters 0 as an argument.

what happens to the program when the following arguments are entered by the user: a) No argument b) 1 c) 0

62

Exceptions Enable You to Handle Errors Gracefully


One of the key benefits of exception handling is that it enables your program to respond to an error and then continue running. Once an exception has been handled, it is removed from the system. Therefore, in the program, each pass through the loop enters the try block anew; any prior exceptions have been handled. This enables your program to handle repeated errors.

63

Exceptions Enable You to Handle Errors Gracefully


As the output confirms, each catch statement responds only to its own type of exception. In general, catch expressions are checked in the order in which they occur in a program. Only a matching statement is executed. All other catch blocks are ignored.

64

Catching Subclass Exceptions


In this case, catch(Throwable) catches all exceptions except for ArrayIndexOutOfBo unds-Exception. The issue of catching subclass exceptions becomes more important when you create exceptions of your own.

65

Why would I want to catch superclass exceptions?


1. if you add a catch clause that catches exceptions of type Exception, then you have effectively added a catch all clause to your exception handler that deals with all program-related exceptions. Such a catch all clause might be useful in a situation in which abnormal program termination must be avoided no matter what occurs. 2. in some situations, an entire category of exceptions can be handled by the same clause. Catching the superclass of these exceptions allows you to handle all without duplicated code.

66

Try Blocks Can Be Nested


One try block can be nested within another. An exception generated within the inner try block that is not caught by a catch associated with that try is propagated to the outer try block. For example, here the ArrayIndexOutOfBoundsException is not caught by the inner catch, but by the outer catch.

67

Try Blocks Can Be Nested

68

The Finally Keyword


Finally, youll now incorporate the finally keyword to try-catch statements! Here is how this reserved word fits in: try { <code to be monitored for exceptions> } catch (<ExceptionType1> <ObjName>) { <handler if ExceptionType1 occurs> } ... } finally { <code to be executed before the try block ends> }

69

Vous aimerez peut-être aussi