Outline

Preview:

DESCRIPTION

Outline. Creating Objects The String Class Packages Formatting Output Enumerated Types Wrapper Classes Components and Containers Images. Formatting output. It is often necessary to format values output looks appropriate when printed or displayed - PowerPoint PPT Presentation

Citation preview

Chapter 5: Conditionals and loops

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

OutlineAltering flow of control

Boolean expressions

Conditional Statements

The while Statement

Other Repetition Statements

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

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

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.

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

Conditional expressions

All conditionals and loops are based on conditional expressions

called Boolean expressions

Use Equality operators

Relational operators

Logical operators

OutlineAltering flow of control

Boolean expressions

Conditional Statements

The while Statement

Other Repetition Statements

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”);

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

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

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

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

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

OutlineAltering flow of control

Boolean expressions

Conditional Statements

The while Statement

Other Repetition Statements

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

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

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

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

Logic of an if-else statement

conditionevaluated

statement1

true false

statement2

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

}

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

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

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

Conditional operator (cont’d)

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

is equivalent to

if (total > Max)total = total + 1

else

total = total * 2

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

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++;}

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?

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”);

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

}

}

Comparing data

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

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

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

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

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

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

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

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

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

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"

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

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

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

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

The switch Statement

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

An example of a switch statement:

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

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

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

OutlineAltering flow of control

Boolean expressions

Conditional Statements

The while Statement

Other Repetition Statements

Recommended