Presentation is loading. Please wait.

Presentation is loading. Please wait.

Pemrograman Dasar Smt I 2004/2005

Similar presentations


Presentation on theme: "Pemrograman Dasar Smt I 2004/2005"— Presentation transcript:

1 Pemrograman Dasar Smt I 2004/2005
Control Statement Pemrograman Dasar Smt I 2004/2005

2 Statement (review) The statement is the main building block from which code sequences are constructed. Statements are executed in the order listed and are always terminated by a semicolon. expr; or { expr1; expr2; … exprn; } 11/27/2018 8:32 PM Control Statements

3 Control Flow Statement
We use control flow statement to conditionally execute statements, to repeatedly execute a block of statements, and to otherwise change the normal, sequential flow of control. For example, in the following code snippet, the if statement conditionally executes the System.out.println statement within the braces, based on the return value of Character.isUpperCase(aChar): char c; ... if (Character.isUpperCase(aChar)) { System.out.println("The character " + aChar + " is upper case."); } 11/27/2018 8:32 PM Control Statements

4 Control Flow Statement in Java
Statement Type Keyword Looping while, do-while , for Decision making if-else, switch-case Exception handling try-catch-finally, throw branching break, continue, label:, return 11/27/2018 8:32 PM Control Statements

5 The if Statement used to conduct a conditional test and execute a block of statements if the test evaluates to true. Syntax: Note you can layout code in any way you want. if ( booleanExpression ) {statement} if ( booleanExpression ) { statement } else 11/27/2018 8:32 PM Control Statements

6 Example If Else public class IfElseDemo {
public static void main(String[] args) { int testscore = 76; 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'; } System.out.println("Grade = " + grade); 11/27/2018 8:32 PM Control Statements

7 The output from this program is: Grade = C
You may have noticed that the value of testscore can satisfy more than one of the expressions in the compound if statement: 76 >= 70 and 76 >= 60. However, as the runtime system processes a compound if statement such as this one, once a condition is satisfied, the appropriate statements are executed (grade = 'C';), and control passes out of the if statement without evaluating the remaining conditions. 11/27/2018 8:32 PM Control Statements

8 Example If Else 2 import java.util.*; public class Morning {
public static void main( String args[] ) { Calendar rightNow = Calendar.getInstance(); if ( rightNow.get( Calendar.AM_PM ) == Calendar.AM ) System.out.println( "Good morning..." ); else System.out.println( "Good afternoon..." ); } 11/27/2018 8:32 PM Control Statements

9 Dangling Else The else clause is always associated with the nearest if
Use { … } to change the association if ( booleanExpression ) statement else 11/27/2018 8:32 PM Control Statements

10 The switch statement used to evaluate a variable that can later be matched with a value specified by the "case" keyword in order to execute a group of statements. The default case is optional. Syntax: switch ( expression ) { case char/byte/short/int constant : statementSequence default: statementSequence 11/27/2018 8:32 PM Control Statements

11 Example public class SwitchDemo {
public static void main(String[] args) { int month = 8; 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; } 11/27/2018 8:32 PM Control Statements

12 Example public class SwitchDemo2 {
public static void main(String[] args) { int month = 2; int year = 2000; int numDays = 0; 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; case 2: if ( ((year % 4 == 0) && !(year % 100 == 0)) || (year % 400 == 0) ) numDays = 29; else numDays = 28; break; } System.out.println("Number of Days = " + numDays); } } Example 11/27/2018 8:32 PM Control Statements

13 Switch-Example 3 We 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 = 8; . . . 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; } 11/27/2018 8:32 PM Control Statements

14 The while Loop While : “used to declare a loop that iterates a block of statements. The loop`s exit condition is specified as part of the while statement.” Syntax: while ( booleanExpression ){ statement } 11/27/2018 8:32 PM Control Statements

15 Divide public class Divide {
public static void main( String args[] ) { int dividend = 35; int divisor = 5; int remainder = dividend; int quotient = 0; while ( remainder >= divisor ) { remainder = remainder - divisor; quotient = quotient + 1; } System.out.println( dividend + " / " + divisor + " = " + quotient); dividend + " % " + divisor + " = " + remainder ); } // Divide 11/27/2018 8:32 PM Control Statements

16 Square Root public class SquareRoot {
public static void main( String args[] ) { double epsilon = 1.0e-9; double number = 2.0; double oldGuess = 0; double newGuess = number; while ( Math.abs( newGuess - oldGuess ) > epsilon ) { oldGuess = newGuess; newGuess = ( ( number / oldGuess ) + oldGuess ) / 2.0; } System.out.println( “The square root of “ + number + “ is “ +newGuess ); } // SquareRoot 11/27/2018 8:32 PM Control Statements

17 The do-while Loop do-while evaluates the expression at the bottom. Thus the statements associated with a do-while are executed at least once. Syntax: do { statement(s) } while ( booleanExpression ); 11/27/2018 8:32 PM Control Statements

18 The for Loop Syntax: The initialization is an expression that initializes the loop-it's executed once at the beginning of the loop. The termination expression determines when to terminate the loop. This expression is evaluated at the top of each iteration of the loop. When the expression evaluates to false, the loop terminates. Finally, increment is an expression that gets invoked after each iteration through the loop. Each of the expressions is optional, the semicolons are not. for (initialization; termination; increment) { statement } 11/27/2018 8:32 PM Control Statements

19 Often for loops are used to iterate over the elements in an array, or the characters in a string.
The following sample, ForDemo, uses a for statement to iterate over the elements of an array and print them: public class ForDemo { public static void main(String[] args){ int[] arrayOfInts = {32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; for (int i = 0; i < arrayOfInts.length; i++) { System.out.print(arrayOfInts[i] + " "); } System.out.println(); 11/27/2018 8:32 PM Control Statements

20 Factorial public class Factorial {
public static void main( String args[] ) { int num = 5; int fact = 1; for ( int i = 1; i <= num; i++ ) fact = fact * i; System.out.println( fact ); } } // Factorial 11/27/2018 8:32 PM Control Statements

21 CharCount public class CharCount {
public static void main( String args[] ) { String theString = "Now is the time for all good people ... "; char target = 't'; int count = 0; for ( int i = 0; i < theString.length(); i++ ) if ( theString.charAt( i ) == target ) count++; System.out.println( target + " appears " + count + " times" ); } } // CharCount 11/27/2018 8:32 PM Control Statements

22 Reverse // This program reverses a given string public class Reverse {
public static void main( String args[] ) { String orig = "Hello World"; String reverse = ""; for (int i = 0; I < orig.length(); i++) reverse = orig.charAt( i ) + reverse; System.out.println( reverse ); } } // Reverse 11/27/2018 8:32 PM Control Statements

23 Mult public class Mult { public static void main( String args[] ) {
for ( int i = 0; i < 10; i++ ) { for ( int j = 0; j < 10; j++ ) { if ( i * j < 10 ) System.out.print( " " ); System.out.print( ( i * j ) + " " ); } System.out.println(); } // Mult 11/27/2018 8:32 PM Control Statements

24 Transfer Statements The break statement can occur anywhere within a switch, for, while or do statement and causes execution to jump to the next statement. The continue statement can occur anywhere within a for, while or do statement and causes execution to jump to the end of the loop body. 11/27/2018 8:32 PM Control Statements

25 Exception Handling Statements
Exception is an event during program execution that prevents the program from continuing normally; generally, an error. It means that the normal flow of the program is interrupted and that the runtime environment attempts to find an exception handler--a block of code that can handle a particular type of error. The exception handler can attempt to recover from the error or, if it determines that the error is unrecoverable, provide a gentle exit from the program. The Java supports exceptions with the try, catch, and throw keywords. 11/27/2018 8:32 PM Control Statements

26 Try-Catch-finally Three statements play a part in handling exceptions:
The try statement identifies a block of statements within which an exception might be thrown. The catch statement must be associated with a try statement and identifies a block of statements that can handle a particular type of exception. The statements are executed if an exception of a particular type occurs within the try block. The finally statement must be associated with a try statement and identifies a block of statements that are executed regardless of whether or not an error occurs within the try block. 11/27/2018 8:32 PM Control Statements

27 Exception Handling Syntax try { statement(s)
} catch (exceptiontype name) { } finally { } 11/27/2018 8:32 PM Control Statements

28 Branching Statement Java support 3 branching statement:
The break statement The continue statement The return statement 11/27/2018 8:32 PM Control Statements

29 Branching #1 : Break The break statement has two forms: unlabeled and labeled. The unlabeled form of the break statement used with switch earlier. Unlabeled break terminates the enclosing switch statement, and flow of control transfers to the statement immediately following the switch. We can also use the unlabeled form of the break statement to terminate a for, while, or do-while loop. The following sample program, BreakDemo , contains a for loop that searches for a particular value within an array: 11/27/2018 8:32 PM Control Statements

30 Unlabeled-Break Example
public class BreakDemo { public static void main(String[] args) { int[] arrayOfInts = { 32, 87, 3, 589, 12, 1076, 2000, 8, 622, 127 }; int searchfor = 12; int i = 0; boolean foundIt = false; for ( ; i < arrayOfInts.length; i++) { if (arrayOfInts[i] == searchfor) { foundIt = true; break; } if (foundIt) { System.out.println("Found " + searchfor + " at index " + i); } else { System.out.println(searchfor + "not in the array"); 11/27/2018 8:32 PM Control Statements

31 Branching: Labeled-Break
The labeled form terminates an outer statement, which is identified by the label specified in the break statement. The following program, BreakWithLabelDemo, is similar to the previous one, but it 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: 11/27/2018 8:32 PM Control Statements

32 Labeled-Break Example
public class BreakWithLabelDemo { public static void main(String[] args) { int[][] arrayOfInts = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 } }; int searchfor = 12; int i = 0; int j = 0; boolean foundIt = false; search: for ( ; i < arrayOfInts.length; i++) { for (j = 0; j < arrayOfInts[i].length; j++) { if (arrayOfInts[i][j] == searchfor) { foundIt = true; break search; } if (foundIt) { System.out.println("Found " + searchfor + " at " + i + ", " + j); } else { System.out.println(searchfor + "not in the array"); Labeled-Break Example 11/27/2018 8:32 PM Control Statements

33 Branching #2 : Continue Statement
We use the continue statement to skip the current iteration of a for, while , or do-while loop. 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. The following program, ContinueDemo , steps through a string buffer checking each letter. If the current character is not a p, the continue statement skips the rest of the loop and proceeds to the next character. If it is a p, the program increments a counter, and converts the p to an uppercase letter. 11/27/2018 8:32 PM Control Statements

34 Continue - Example public class ContinueDemo {
public static void main(String[] args) { StringBuffer searchMe = new StringBuffer( "peter piper picked a peck of pickled peppers"); int max = searchMe.length(); int numPs = 0; for (int i = 0; i < max; i++) { //interested only in p's if (searchMe.charAt(i) != 'p') continue; //process p's numPs++; searchMe.setCharAt(i, 'P'); } System.out.println("Found " + numPs + " p's in the string."); System.out.println(searchMe); 11/27/2018 8:32 PM Control Statements

35 Branching #3: Return Statement
The last of Java's branching statements is the return statement. We use return 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: 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: return value: return: 11/27/2018 8:32 PM Control Statements


Download ppt "Pemrograman Dasar Smt I 2004/2005"

Similar presentations


Ads by Google