Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

27
Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Transcript of Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 1: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Chapter 3

Flow of Control

Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Page 2: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

As in most programming languages, flow of control in Java refers to its branching and looping mechanisms

Flow of Control

Flow of Control

Branching

Switch case if If… else

Looping

For while Do.. while

Page 3: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

د/احمد يوسف 3

Control Structures

Page 4: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

4

Branching Statements

– Simple if statement

– if-else statement

– Nested if statements

– switch statement

Page 5: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

5

Page 6: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Java Comparison Operators

3-6

Page 7: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

د/احمد يوسف 7

Simple if Statement

Syntax:if (expression) statement ;

if (hour < 12)System.out.println("Good morning.");

Page 8: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

د/احمد يوسف

Example: Simple if Statement

import java.util.Scanner;public class Result{public static void main(String[] args){

Scanner keyboard=new Scanner(System.in);

int grade= keyboard.nextInt();

if ( grade > = 60 )

System.out.println ( " passed " ); }}

Page 9: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

9

Example: Simple if Statement Write a Java program prints the absolute value of a number.import java.util.Scanner;class absolute {

public static void main(String [] args) { Scanner kb = new Scanner(System.in); System.out.print(" Enter a number: "); int x = kb.nextInt(); int y = x;

if( y < 0) y = -y;

System.out.print(" The absolute value of " + x + " is " + y); }}

Page 10: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

د/احمد يوسف 10

Branching with an if-else Statement Two-Way Selection

Syntax:if (expression)

statement1;else statement2;

The Expression must be enclosed in parenthesesIf the Expression is true, then the Statement1 is executedIf the Expression is false, then the Statement2 is executed

Page 11: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Example: Even/Odd number

import java.util.Scanner;class EvenOdd{

public static void main(String [] args) { Scanner kb = new Scanner(System.in); System.out.print(" Enter a number: "); int num= kb.nextInt();

if(num %2 = = 0)

System.out.println ( " The Number is Even" );

else

System.out.println ( "The Number is Odd" );

}

} 3-11

Page 12: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

د/احمد يوسف 12

if ( grade > = 60 )System.out.println (" passed " );

elseSystem.out.println (" failed " );

Page 13: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

13

Compound (Block of) StatementsSyntax:{

statement1statement2

.

.

.statementn

}

Page 14: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Compound Statements• You have to use braces if the <then> or <else> block has multiple statements. • if only one statement is there braces are optional but it is advisable to always

use them to enhance readability

if (testScore < 60)

{

System.out.println("You did not pass");

System.out.println("Try harder next time");

}

else

{

System.out.println("You did pass");

System.out.println("Keep up the good work");

}

Then BlockThen Block

Else BlockElse Block

Page 15: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Multiway if-else Statementif (Boolean_Expression) Statement_1else if (Boolean_Expression) Statement_2 else if (Boolean_Expression_n) Statement_nelse Statement_For_All_Other_Possibilities

. . .

3-15

Page 16: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

if - else- if

if (score >= 90) {System.out.println("Grade is A");

} else if (score >= 80) {System.out.println("Grade is B");

} else if (score >= 70) {System.out.println("Grade is C");

} else if (score >= 60) {System.out.println("Grade is D");

} else {System.out.println("Grade is F");

}

Test Score Grade90 score A80 score 90 B70 score 80 C60 score 70 D score 60 F

Page 17: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

The switch Statement• The switch statement is multiway branching

– When a switch statement is evaluated, one of a number

of different branches is executed

– The choice of which branch to execute is determined by a

controlling expression enclosed in parentheses after the

keyword switch

• The controlling expression must evaluate to a char, int, short,

or byte

3-17

Page 18: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

The switch Statement

• Each branch statement in a switch statement starts with

the reserved word case, followed by a constant called a case

label, followed by a colon, and then a sequence of statements

– Each case label must be of the same type as the controlling expression

– Each sequence of statements may be followed by a break statement

( break;)

3-18

Page 19: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

د/احمد يوسف 19

switch Structures

Page 20: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

د/احمد يوسف 20

switch (expression){

case value 1: statements 1; break;

case value 2: statements 2; break;

...case value n: statements n ;

break;default: statements

}

Page 21: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

د/احمد يوسف 21

switch With No break Statements

x = 10;x = 10;

false

truech == 'a' ?

ch == 'a' ?

x = 20;x = 20;

x = 30;x = 30;

ch == 'b' ?

ch == 'b' ?

ch == 'c' ?

ch == 'c' ?

false

false

true

true

public class SwitchNoBreak { public static void main( String s[] ) { char ch = 'a'; int x = 0;

switch ( ch ) { case 'a': x = 10; case 'b': x = 20; case 'c': x = 30; } System.out.println( "x = " + x ); }}

x = 30

Page 22: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

د/احمد يوسف 22

switch With break Statements

x = 10;x = 10;

false

truech == 'a' ?

ch == 'a' ?

x = 20;x = 20;

x = 30;x = 30;

ch == 'b' ?

ch == 'b' ?

ch == 'c' ?

ch == 'c' ?

false

false

true

true

break;break;

break;break;

break;break;

public class SwitchWithBreak { public static void main(String s[]) { char ch = 'a'; int x = 0;

switch ( ch ) { case 'a': x = 10; break; case 'b': x = 20; break; case 'c': x = 30; break; } System.out.println( "x = " + x ); }}

x = 10

Page 23: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

د/احمد يوسف 23

import java.util.Scanner;

class Arithmatic{

public static void main(String [ ] args){

Scanner keyboard=new Scanner(System.in);

System.out.print("Enter First number"); int x= keyboard.nextInt();

System.out.print("Enter Second number“); int y= keyboard.nextInt();

System.out.print("Enter 1:Add\n 2:Sub\n 3:Mul.\n 4: Div.“);

int menu = keyboard.nextInt(); switch (menu) {

case 1 : System.out.println(“x+y = " + (x+y) ); break ;case 2 : System.out.println(“ x – y =" + (x - y)) ; break ;case 3 : System.out.println("x * y ="+ (x * y)) ; break ;case 4 : System.out.println("x / y ="+ (x / y)) ; break ;

}}}

Page 24: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

The Conditional Operator• The conditional operator is a notational variant on certain forms of the

if-else statement– Also called the ternary operator or arithmetic if– The following examples are equivalent:

if (n1 > n2) max = n1;

else max = n2;

vs.max = (n1 > n2) ? n1 : n2;

– If the Boolean expression is true, then the expression evaluates to the value of the first expression (n1), otherwise it evaluates to the value of the second expression (n2)

3-24

Page 25: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Pitfall: Using == with Strings

• The equality comparison operator (==) can correctly test two

values of a primitive type

• In order to test two strings to see if they have equal values,

use the method equals, or equalsIgnoreCase

string1.equals(string2)

string1.equalsIgnoreCase(string2)

3-25

Confusion between =, ==, and

equals method is one of the most

frequent programming errors

Page 26: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Building Boolean Expressions• When two Boolean expressions are combined using the "and" (&&)

operator, the entire expression is true provided both expressions are true– Otherwise the expression is false

• When two Boolean expressions are combined using the "or" (||) operator, the entire expression is true as long as one of the expressions is true– The expression is false only if both expressions are false

• Any Boolean expression can be negated using the ! operator– Place the expression in parentheses and place the ! operator in front of it

• Unlike mathematical notation, strings of inequalities must be joined by &&– Use (min < result) && (result < max) rather than

min < result < max

3-26

Page 27: Chapter 3 Flow of Control Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Copyright © 2010 Pearson Addison-Wesley. All rights reserved.

Truth Tables

3-27