20090727100707mts 2023 Chp 4

  • Uploaded by: muru85
  • 0
  • 0
  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View 20090727100707mts 2023 Chp 4 as PDF for free.

More details

  • Words: 3,135
  • Pages: 66
MTS 2023 Object Oriented Programming Control Statements

1

Control Structures 





A computer can process a program in 3 ways:  Sequence  Selection – the program executes particular statements depending on some condition (s)  Repetition – the program repeats particular statements a certain number of times depending on some condition (s) Selection Statements  Using if and if...else  Nested if Statements  Using switch Statements  Conditional Operator Repetition Statements  Looping: while, do, and for  Nested loops  Using break and continue 2

Relational Operators 





To make decisions, you must be able to express conditions and make comparisons An expression that has a value either true or false is called logical (Boolean) Example : i > j , it will have the value true if the value i is greater than the value of j; otherwise it will have the value false

3

Relational Operators Operator == != < <= > >= 

Description Equal to Not equal to Less than Less than or equal to Greater than Greater than or equal to

Example :  

8 < 15  true 6 != 6  false 4

Comparing strings 



Strings are compared character by character starting with the first character. The class String provides the method compareTo to compare objects of the class String 

Syntax : str1.compareTo(str2)    

where str1 and str2 are string variable. An integer value < 0 if string str1 is less than string str2 An integer value 0 if string str1 is equal to string str2 An integer value > 0 if string str1 is greater than string str2 5

Comparing strings 

 

The class String also provides the method equals to determine whether two Strings contain the same value Returns the value true or false Example:  

str1.equals(“Hello”)  true Str1.equals(str2)  false

6

Comparing strings 

Example : String str1 = “Hello”; String str2 = “Hi”; String str3 = “Bigger”; str1.compareTo (str2)  value : < 0 str1.compareTo (“Hen”) value : < 0 str2.compareTo(“Hi”)  value : = 0 str3.compareTo (“Big”)  value : > 0

7

Logical (Boolean) Operators 

3 logical (boolean) operators: 





not (!)

and (&&)

or (||)

Expression

! (Expression)

True

False

False

True

Expression1

Expression2

Expression1 && Expression2

True

True

True

True

False

False

False

True

False

False

False

False

Expression1

Expression2

Expression1 || Expression2

True

True

True

True

False

True

False

True

True

False

False

False 8

Order of precedence 1. 2. 3. 4. 5. 6. 7.

! , + , - (unary operator) *,/,% +, -, <, <=, >=, > ==, != && || = (assignment operator)

9

Logical (Boolean) Operators 

Example :      

(14 >= 5) | | (‘A’ > ‘B’)  true (14 >= 5) && (‘A’ < ‘B’)  true ! (‘A’ > ‘B’)  true !(6 <= 7)  false 11 > 5 | | 6 < 15 && 7 >= 8  true (17 < 4 * 3 + 5) || (8 * 2 == 4 * 4) && !(3+3 == 6)  false

10

Selection Statements 

if Statements



switch Statements



Conditional Operators

11

if Statements 

Syntax: if (booleanExpression) { statement(s); }





If the value of the booleanExpression is true, the statement (s) executes. If the value is false, the statement (s) does not executes and it goes on to the next statement in the program. 12

if Statements

True Expression Statement False

13

if Statements public class TestIf { public static void main (String [] args) { int i = 5; if ((i >= 0) && (i <= 10)) System.out.println("i is an integer between 0 and 10"); } } 14

The if...else Statement 

 

Syntax: if (booleanExpression) { statement(s)_1; } else { statement(s)_2; } Statement(s)_1 will be executed if the expression value is true Statement(s)_2 will be executed if the expression value is false 15

The if...else Statement

True Expression Statement_1 False Statement_2

16

The if...else Statement public class TestIfElse { public static void main (String [] args) { int i = 100; if ((i >= 0) && (i <= 10)) System.out.println("i is an integer between 0 and 10"); else System.out.println("i is NOT an integer between 0 and 10"); } }

17

Syntax for the if Statement if ( ) else Boolean Expression

<else block>

if (

Then Block

testScore < 70

)

JOptionPane.showMessageDialog(null, "You did not pass" ); else

Else Block

JOptionPane.showMessageDialog(null, "You did pass " ); 18

Nested if Statements 

Syntax: if (expression_1) statement_1; else if (expression_2) statement_2; ……… . else if(expression_n ) statement _n; else last_statement; 19

if-else-if statement 



In this nested form, expression_1 is first evaluated. If it is not zero, statement_1 is executed and the whole statement terminated. On the other hand, if expression_1 is zero, control passes to the else if part and expression_2 is evaluated. If it is not zero, statement_2 is executed and the whole statement is terminated. 20

if-else-if statement 





If it is zero, other else if parts (if any) are tested in a similar way. Finally, if expression_n is not zero, statement_n is executed; if not, last_statement is executed. Only ONE of the statements will be executed.

21

Matching else Are

A and B different?

if (x < y) if (x < z)

A

System.out.print("Hello");

Both

A and B means…

if (x < y) { if (x < z) {

else

System.out.print("Hello");

System.out.print("Good bye");

} else { bye"); if (x < y) if (x < z)

B

System.out.print("Good

} }

System.out.print("Hello"); else System.out.print("Good bye");

22

Conditional Operator  



It provides a shorthand method of expressing a simple if/else statement. Syntax: expression ? expression : expression;

Example: if (x > 0) y=1 else y = -1; is equivalent to y = (x > 0) ? 1 : -1;

23

switch Statements 



The switch construct is an elegant alternative to the more complex if-else-if construct which is more difficult to read and understand. switch statement just can be implemented for expression with an integer or character constant

24



Syntax: switch (expression) { case expression_1 : statement_1; break; case expression_2 : statement_2; break; case expression_3 : statement_3; break; case expression_4 : statement_4; break; . . case const_n : statement_n; break; default : statementA; } 25



When the switch statement is executed, the expression is first evaluated. 







If it evaluates to expression_1, the statement sequence for case expression_1 is executed followed by the break which terminates the entire switch statement. If it evaluates to expression_2, then the statement sequence for case expression_2 is executed followed by break which then terminates the switch statement; and so on. If it evaluates to none of the case expressions, the statement sequence for the default case is executed, thus terminating the switch statement.

break statement is used to exit a switch statement. If it is left out, the program "falls through" the remaining statements in the switch statement 26

switch Statements switch (year) { case 7: annualInterestRate = 7.25; break; case 15: annualInterestRate = 8.50; break; case 30: annualInterestRate = 9.0; break; default: System.out.println ("Wrong number of years, enter 7, 15, or 30"); }

27

The switch Statement int gradeLevel; gradeLevel = JOptionPane.showInputDialog(“Semester :" ); switch (gradeLevel) { case 1: System.out.print("Go to the Gymnasium"); break;

This statement is executed if the gradeLevel is equal to 1.

case 2: System.out.print("Go to the Auditorium"); break; case 3: System.out.print("Go to Hall"); break; case 4: System.out.print("Go to Lab"); break;

This statement is executed if the gradeLevel is equal to 4.

}

28

Syntax for the switch switch ( <arithmetic expression> ) { Statement : : } switch (

Arithmetic Expression

gradeLevel

) {

case 1: System.out.print("Go to the Gymnasium"); break;

Case Label

case 2: System.out.print("Go to the Auditorium"); break; case 3: System.out.print("Go to Hall"); break;

Case Body

case 4: System.out.print("Go to Lab"); break; } 29

switch With No break Statements switch ( N ) { case 1: x = 10; case 2: x = 20; case 3: x = 30; }

N == 1?

true x = 10;

false N == 2?

true x = 20;

false N == 3?

true x = 30;

false

30

switch With break Statements switch ( N ) { case 1: x = 10; break; case 2: x = 20; break; case 3: x = 30; break; }

N == 1?

true x = 10;

false N == 2?

break;

true x = 20;

false N == 3?

false

break;

true x = 30; break;

31

switch With the default Block switch (ranking) { case 10: case

9:

case

8: System.out.print(“Undergraduate"); break;

case

7:

case

6: System.out.print(“Master"); break;

case

5:

case

4: System.out.print(“PhD"); break;

default: System.out.print("Input error: Invalid Data"); break; } 32

Repetition 







Repetition statements control a block of code to be executed for a fixed number of times or until a certain condition is met. Count-controlled repetitions terminate the execution of the block after it is executed for a fixed number of times. Sentinel-controlled repetitions terminate the execution of the block after one of the designated values called a sentinel is encountered. Repetition statements are called loop statements also. 33

Repetitions 

while Loops



do Loops



for Loops



break and continue

34

while Loop Flow Chart 



if true, then statement is executed, and expression is evaluated again if false, then the loop is finished and next statement is executed

35

The while Statement int sum = 0, number = 1; while ( number <= 100 ) { sum

=

sum + number;

number = number + 1;

These statements are executed as long as number is less than or equal to 100.

}

36

Syntax for the while Statement while ( ) <statement> Boolean Expression

while ( sum

Statement (loop body)

number <= 100 =

) {

sum + number;

number = number + 1; }

37

Control Flow of while int sum = 0, number = 1

number <= 100 ?

false

true

sum = sum + number; number = number + 1;

38

More Examples 1

int sum = 0, number = 1; while ( sum <= 1000000 ) { sum

=

sum + number;

Keeps adding the numbers 1, 2, 3, … until the sum becomes larger than 1,000,000.

number = number + 1; }

2

int product = 1, number = 1, count = 20, lastNumber;

Computes the product of the first 20 odd integers.

lastNumber = 2 * count - 1; while (number <= lastNumber) { product = product * number; number

= number + 2;

}

39

Example while Loops 

Example i =0; while (i < = 20) { System.out.print(i + “ “); i = i + 5; }

Output: 0 5 10 15 20

40

Example: Testing Input Data String inputStr; int

Priming Read

age;

inputStr = JOptionPane.showInputDialog(null, "Your Age (between 0 and 130):"); age

= Integer.parseInt(inputStr);

while (age < 0 || age > 130) { JOptionPane.showMessageDialog(null, "An invalid age was entered. Please try again."); inputStr = JOptionPane.showInputDialog(null, "Your Age (between 0 and 130):"); age = Integer.parseInt(inputStr); } 41

Watch Out for Pitfalls n n

n

n

Watch out for the off-by-one error (OBOE). Make sure the loop body contains a statement that will eventually cause the loop to terminate. Make sure the loop repeats exactly the correct number of times. If you want to execute the loop body N times, then initialize the counter to 0 and use the test condition counter < N or initialize the counter to 1 and use the test condition counter <= N.

42

Loop Pitfall - 1 1

int product = 0; while ( product < 500000 ) { product = product * 5; }

Infinite Loops

2

int count = 1; while ( count != 10 ) { count = count + 2; }

Both loops will not terminate because the boolean expressions will never become false.

Overflow 





An infinite loop often results in an overflow error. An overflow error occurs when you attempt to assign a value larger than the maximum value the variable can hold. In Java, an overflow does not cause program termination. With types float and double, a value that represents infinity is assigned to the variable. With type int, the value “wraps around” and becomes a negative value. 44

Loop Pitfall - 2 1

float count = 0.0f; while ( count != 1.0f ) { count = count + 0.3333333f; }

2

//seven 3s

float count = 0.0f;

Using Real Numbers Loop 2 terminates, but Loop 1 does not because only an approximation of a real number can be stored in a computer memory.

while ( count != 1.0f ) { count = count + 0.33333333f; }

//eight 3s

45

Loop Pitfall – 2a 1

int result = 0; double cnt = 1.0; while (cnt <= 10.0){ cnt += 1.0; result++; } System.out.println(result);

2

10

int result = 0; double cnt = 0.0;

Using Real Numbers Loop 1 prints out 10, as expected, but Loop 2 prints out 11. The value 0.1 cannot be stored precisely in computer memory.

while (cnt <= 1.0){ cnt += 0.1; result++; } System.out.println(result);

11 46

Loop Pitfall - 3 

1

Goal: Execute the loop body 10 times. count = 1;

2

while ( count < 10 ){

while ( count <= 10 ){

. . .

. . .

count++;

count++;

}

3

}

count = 0; while ( count <= 10 ){

}

count = 1;

4

count = 0; while ( count < 10 ){

. . .

. . .

count++;

count++; }

1 and 3 exhibit off-by-one error. 47

Counter-controlled while loops 

A set of statements need to be executed N times counter = 0; while (counter < N) { …. counter ++; } 48

Sentinel-controlled while  You might know exactly how many times a set of loops statements needs to be executed, but you do know that the statements need to be executed until a special value is met (sentinel). input the first data item into variable while (variable != sentinel) { ……. input a data item into variable …… }

49

do Loops Syntax: do { // Loop body; } while (continue-condition); 



execute the loop, then test the continue-condition

50

Syntax for the do-while do Statement <statement>

while ( ) ; do

{ sum += number; number++;

}

while ( );

Statement (loop body)

sum <= 1000000

Boolean Expression

51

Control Flow of do-while int sum = 0, number = 1

sum += number; number++;

sum <= 1000000 ?

false

true



Example: a = 0; do { System.out.print (a + “ “); a = a + 5; } while (a < = 20);

Output: 0 5 10 15 20 53

for Loop 



To simplify the writing of counter-controlled loops Syntax: for(initialization; test; update) statement; n n

Perform initialization Evaluate test expression  

n

If true, execute statement If false, terminate loop execution

Execute update, then re-evaluate test expression 54

Syntax for the for Statement for ( ; ;

)

<statement> Boolean Expression

Initialization

for (

i = 0

;

i < 20

number = scanner.nextInt(); sum += number;

Increment

;

i++

) { Statement (loop body)

}

55

Control Flow of for i = 0;

false

i < 20 ?

true number = . . . ; sum += number;

i ++;

56

Example for Loops int i = 0; while (i < 100) { System.out.println("Welcome to Java! ” + i); i++; } Example: int i; for (i = 0; i<100; i++) { System.out.println("Welcome to Java! ” + i); }

57

for Loop Flow Chart

58

for Loop Examples 

Examples for using the for loop: 





for (a = 0; a <10; a++) System.out.print(a + “ “); output: ?? for (a = 1; a<=5; a++) { System.out.print(“FTMK“); System.out.print(“*“); }



output: ?? 59

The break Keyword 

Used for two purposes: 





To exit early from the loop To skip the remainder of the switch structure

After the break statement executes, the program continues to execute starting at the first statement after the structure 60

The continue Keyword 







Used in while, for, and do…while structure When the continue statement is executed in a loop, it skips the remaining statements in the loop and proceed with the next iteration of the loop. In a while or do..while structure, the loop –continue test is evaluated immediately after the continue statement In a for structure, the update statement is executed after the continue statement and then the loop condition executes

61

Example Using break public class TestBreak { public static void main(String[] args) { int sum = 0; int item = 0; do { item ++; sum += item; if (sum >= 6) break; } while (item < 5); System.out.println("The sum is " + sum); //pause System.out.println("Press Ctrl+C to close this window ......"); MyInput.readInt(); } }

62

Example Using continue class TestContinue { public static void main(String[] args) { int sum = 0; int item = 0; do { item++; if (item == 2) continue; sum += item; } while (item < 5); System.out.println("The sum is " + sum); //pause System.out.println("Press Ctrl+C to close this window ......"); MyInput.readInt(); } } 63

Exercises – if and switch 1. 2.

3.

4.

Write an if statement that sets the variable num to 1 when choice equals 10. Write an if statement that sets the variable num to the same value as the control variable choice when choice equals 5, but sets num to 0 in every other case. Write an if statement that sets the variable num to twice the value of the control variable choice. Valid values for choice are 3, 4, 5, and 6. Convert the if statement in exercise 3 to a switch statement.

64

Exercises – while and dowhile 1. 2.

3. 4.

5.

Write a while loop that executes 20 times. Convert the while loop you wrote in exercise 1 to a do-while loop. Write a while loop that will result in an infinite loop. Write a do-while loop that can never execute more than once. Write a while loop that counts backwards from 20 to 10.

65

Exercises – for loop 1. 2. 3. 4.

Write a for loop that executes 15 times. Write a for loop that counts by twos. Write a for loop that can never execute. Write a for loop that counts backwards from 20 to 10.

66

Related Documents


More Documents from ""