chapter 5: conditionals and loops. 2 conditionals and loops now we will examine programming...

51
Chapter 5: Conditionals and loops

Upload: godfrey-harrison

Post on 13-Jan-2016

241 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Chapter 5: Conditionals and loops

Page 2: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

2

Conditionals and Loops Now we will examine programming statements that allow us to:

make decisions

repeat processing steps in a loop

Chapter 5 focuses on:

boolean expressions

conditional statements

comparing data

repetition statements

Page 3: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

OutlineAltering flow of control

Boolean expressions

Conditional Statements

The while Statement

Other Repetition Statements

Page 4: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Normal flow of control

Flow of control The order in which statements are executed

Execution normally proceeds in a linear fashion JAVA application begins with the first line of the main method

And proceeds step by step to the end of the main method

Some programming statements allow us to decide or not to execute a particular statement

execute a statement over and over, repetitively

Page 5: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Conditional statements

A conditional statement lets us choose which statement will be executed next

is called sometimes selection statement

The Java conditional statement are the if statement

if-else statement

switch statement

Page 6: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

The if statement: syntax The if statement has the following syntax

Example if (count > 20)

System.out.println(“count exceeded”);

if ( condition ) statement;

if is a Javareserved word

The condition must be aboolean expression. It mustevaluate to either true or false.

If the condition is true, the statement is executed.If it is false, the statement is skipped.

Page 7: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Altering the flow of control: loop

Loops allow to execute programs over and over again

based on a boolean expression That determines how many times the statement is executed

include while, do, and for statements

Each type has unique characteristics

Page 8: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Conditional expressions

All conditionals and loops are based on conditional expressions

called Boolean expressions

Use Equality operators

Relational operators

Logical operators

Page 9: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

OutlineAltering flow of control

Boolean expressions

Conditional Statements

The while Statement

Other Repetition Statements

Page 10: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Equality operators

The == and != are called equality operators

== tests whether two values are equal

!= tests whether two values are not equalIf (total != sum)

System.out.println(“total does not equal sum”);

Page 11: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Relational operators

They let us decide relative ordering between values Less than (<)

Greater than (>)

Less than or equal (<=)

Greater than or equal (>=)

Arithmetic operations have higher precedence

Page 12: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Logical operators

Java has three logical operators

They all take Boolean operands And produce Boolean results

Logical NOT is unary operator

Logical AND and OR are binary operators

! Logical NOT

&& Logical AND

|| Logical OR

Page 13: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Logical operators (cont’d)

logical

operator

Description Example Result

! Logical Not ! a True if a is false

and False if a is true

&& Logical AND a && b True if a and b are both true and false

otherwise

|| Logical OR a || b True if a or b are true and false otherwise

Page 14: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Logical operators: truth table

A truth table Shows all possible true-false combinations of terms

Since && and || each have 2 operands There are four possible combinations of conditions a and b

a b a && b a || b

true true true true

true false false true

false true false true

false false false false

Page 15: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Boolean expressions

Consider the example if (total < MAX && !found)

System.out.println(“Completed!.”);

Under what condition would the println executed?

total < MAX

found !foundtotal < MAX && !

found

false false true false

false true false false

true false true true

true true false false

Page 16: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

OutlineAltering flow of control

Boolean expressions

Conditional Statements

The while Statement

Other Repetition Statements

Page 17: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

The if Statement

If statement consists of The reserved word if followed by

a Boolean expression enclosed in parentheses

followed by a statement If (total > amount)

total = total + amount;

See Age.java

Conditionevaluated

true

statement

false

Page 18: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

The if-else statement

Sometimes, we want to do one thing if a condition is true,

and another thing if not

We can add an else to an if to handle this situation

if (height <= MAX)adjustment = 0;

else adjustment = MAX – height;

See Wages.java

Page 19: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

The if Statement

If statement consists of The reserved word if followed by

a Boolean expression enclosed in parentheses

followed by a statement If (total > amount)

total = total + amount;

See Age.java

Conditionevaluated

true

statement

false

Page 20: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

The if-else statement

Sometimes, we want to do one thing if a condition is true,

and another thing if not

We can add an else to an if to handle this situation

if (height <= MAX)adjustment = 0;

else adjustment = MAX – height;

See Wages.java

Page 21: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Logic of an if-else statement

conditionevaluated

statement1

true false

statement2

Page 22: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Using block statements

To do more than one thing as a result Of boolean condition evaluation

Replace any single statement with a block of statement

A block of statement is a collection of statements enclosed in braces

If (guess == answer)System.out.println (“you got it! Good guessing!”);

else {System.out.println (“that is not correct, sorry.”);System.out.println (“the number was ” + answer);

}

Page 23: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Block statements

In an if-else statement The if portion, or the else or both

Could be block statements

if (total > MAX){ System.out.println ("Error!!"); errorCount++;}else{ System.out.println ("Total: " + total); current = total*2;}

Page 24: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Conditional operator

Its syntax is

If the condition is true, expression1 is evaluated

If it is false => expression2 is evaluated

The value of the entire conditional operator Is the value of the selected expression

condition ? expression1 : expression2

Page 25: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Conditional operator (cont’d)

Conditional operator is similar to an if-else statement

is a ternary operator requiring three operands

uses the symbol ? :, which are always separated

((total >MAX) ? total+1 : total * 2

total = ((total >MAX) ? total+1 : total * 2

Page 26: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Conditional operator (cont’d)

total = (total > MAX) ? total+1 : total * 2

is equivalent to

if (total > Max)total = total + 1

else

total = total * 2

Page 27: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

27

The Conditional Operator: Example

Another example:System.out.println ("Your change is " + count

+ ((count == 1) ? "Dime" : "Dimes"));

If count equals 1,

then "Dime" is printed

If count is anything other than 1,

then "Dimes" is printed

Page 28: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

28

Block Statements

Several statements can

be grouped together

into block statement delimited by braces

A block statement can

be used wherever a statement is called for

if (total > MAX){ System.out.println ("Error!!"); errorCount++;}

Page 29: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Nested if statements The statement executed as a result of if

Could be another if statement

This is called a nested if if (code == ‘R’)

if (height <= 20)System.out.println(“Situation

Normal”); else

System.out.println (“Bravo”);

is the else matched to the inner if statement or the outer if statement?

Page 30: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Nested if statements (cont’d) else clause

is matched to the closest unmatched if that preceded it

in the previous example, else is matched to if(height<=20)

To avoid confusion, braces can be used to specify if statement to which an else belongs

if (code == ‘R’) {

if (height <= 20)

System.out.println (“Situation Normal”);

}

else

System.out.println (“Bravo”);

Page 31: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

MinOfThree.Java import java.util.Scanner;

public class MinOfThree {

public static void main(String [] args) {

int num1, num2, num3, min = 0;

Scanner scan = new Scanner (System.in);

System.out.println(“Enter three integers: ”);

num1 = scan.nextInt();

num2 = scan.nextInt();

num3 = scan.nextInt();

if (num1 < num2)

if (num1 < num3)

min = num1;

else

min = num3;

else

if (num2<num3)

min = num2;

else

min = num3;

System.out.println(“Minimum value: “+ min);

}

}

Page 32: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Comparing data

Page 33: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Comparing Data

When comparing data using boolean expressions

understand the nuances of certain data types

Let's examine some key situations:

Comparing floating point values for equality

Comparing characters

Comparing strings (alphabetical order)

Comparing object vs. comparing object references

Page 34: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Comparing Float Values You should rarely use the equality operator (==)

when comparing two floating point values

Two floating point values are equal

if the underlying binary representations match exactly

Computations often result

in slight differences that may be irrelevant

In many situations, you might consider

two floating point numbers to be "close enough"

even if they aren't exactly equal

Page 35: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Comparing Float Values

To determine the equality of two floats, you may want to use the following technique:

if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal");

If the difference between two floating point values

is less than the tolerance,

they are considered to be equal

The tolerance could be set to

any appropriate level, such as 0.000001

Page 36: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Comparing Characters

Java character data is based on

the Unicode character set

Unicode establishes a particular numeric value

for each character, and therefore an ordering

We can use relational operators

on character data based on this ordering

For example,

the character '+' is less than the character 'J'

because it comes before it in the Unicode character set

Page 37: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Comparing Characters In Unicode, the digit characters (0-9)

are contiguous and in order

the uppercase letters (A-Z) & lowercase letters (a-z)

are contiguous and in order

Characters Unicode Values

0 – 9 48 through 57

A – Z 65 through 90

a – z 97 through 122

Page 38: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Comparing Strings Remember that in

Java a character string is an object

The equals method can be called

with strings to determine if

two strings contain the same characters in the same order

The equals method returns a boolean resultif (name1.equals(name2)) System.out.println ("Same name");

Page 39: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Comparing Strings

We cannot use the relational operators

to compare strings

The String class contains

a method called compareTo

to determine if one string comes before another

Page 40: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Comparing Strings

A call to name1.compareTo(name2)

returns zero if name1 and name2

are equal (contain the same characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

Page 41: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Comparing Stringsif (name1.compareTo(name2) < 0) System.out.println (name1 + "comes first");else if (name1.compareTo(name2) == 0) System.out.println ("Same name"); else System.out.println (name2 + "comes first");

Because comparing characters and

strings is based on a character set,

it is called a lexicographic ordering

Page 42: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Lexicographic Ordering Lexicographic ordering is not strictly alphabetical

when uppercase and lowercase characters are mixed

For example,

the string "Great" comes before the string "fantastic"

because all of the uppercase letters

come before all of the lowercase letters in Unicode

Also, short strings come before longer strings

with the same prefix (lexicographically)

Therefore "book" comes before "bookcase"

Page 43: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Comparing Objects The == operator can be applied to objects

it returns true

if the two references are aliases of each other

The equals method is defined for all objects,

but unless we redefine it when we write a class,

it has the same semantics as the == operator

It has been redefined in the String class

to compare the characters in the two strings

Page 44: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

The switch statement

The switch statement Provides another way to decide which statement

To execute next

Evaluates an expression that attempts to match The result of one of several possible cases

Each case contains a value and a list of statements

The flow of control transfer to the statement Associated with the first case value that matches

Page 45: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Switch statement: syntax

The general syntax of switch statement is

switch ( expression ){ case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case ...

}

switchandcaseare

reservedwords

If expressionmatches value2,control jumpsto here

Page 46: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

The switch Statement Often a break statement

is used as last statement in each case's statement list

A break statement

Transfers control to end of the switch statement

If a break statement

is not used, flow of control will continue to the next case

Sometimes this may be appropriate, but often

we want to execute only statements associated with one case

Page 47: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

The switch Statement

switch (option){ case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break;}

An example of a switch statement:

Page 48: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

The switch Statement

A switch statement

can have an optional default case

The default case has no

associated value and simply uses

the reserved word default

If the default case is present,

control will transfer to it if no other case value matches

Page 49: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Switch example switch(idchar) {

case ‘A’: acount = acount+1;break;

case ‘B’:bcount=bcount+1; break;

default:System.out.println(“Error

identifying Character”); }

Type of expression evaluated by switch Char, byte, short, or int

Page 50: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

Use of a switch statement

Sample program A comment is printed according to a user’s grade

Grade = 100 => a perfect score; Grade = 90s (Excellent)..etc

Algorithm Ask user to enter a grade

Based on grade value, print the right comment

See GradeReport.java

Page 51: Chapter 5: Conditionals and loops. 2 Conditionals and Loops Now we will examine programming statements that allow us to: make decisions repeat processing

OutlineAltering flow of control

Boolean expressions

Conditional Statements

The while Statement

Other Repetition Statements