lewis chap 5 - conditionals and loops

85
Chapter 5 Conditionals and Loops 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design  © 2007 Pearson Addison-Wesley . All rights reserved

Upload: oshane-bailey

Post on 06-Apr-2018

234 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 185

Chapter5

Conditionalsand Loops

5TH EDITION

Lewis amp Loftus

javaSoftware SolutionsFoundations of Program Design

copy 2007 Pearson Addison-Wesley All rights reserved

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 285

copy 2007 Pearson Addison-Wesley All rights reserved 5-2

Conditionals and Loops

bull Now we will examine programming statements thatallow us to

make decisionsrepeat processing steps in a loop

bull Chapter 5 focuses on

boolean expressionsconditional statements

comparing datarepetition statementsiteratorsmore drawing techniquesmore GUI components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 385

copy 2007 Pearson Addison-Wesley All rights reserved 5-3

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing DataThe while Statement

Iterators

Other Repetition StatementsDecisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 485

copy 2007 Pearson Addison-Wesley All rights reserved 5-4

Flow of Control

bull Unless specified otherwise the order of statementexecution through a method is linear onestatement after another in sequence

bull Some programming statements allow us todecide whether or not to execute a particular statementexecute a statement over and over repetitively

bull These decisions are based on boolean expressions

(or conditions ) that evaluate to true or falsebull The order of statement execution is called the flow

of control

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 585

copy 2007 Pearson Addison-Wesley All rights reserved 5-5

Conditional Statements

bull A conditional statement lets us choose whichstatement will be executed next

bull Therefore they are sometimes called selection

statements bull Conditional statements give us the power to

make basic decisions

bull

The Java conditional statements are theif statement if-else statement switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 685

copy 2007 Pearson Addison-Wesley All rights reserved 5-6

The if Statement

bull The if statement has the following syntax

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 executedIf it is false the statement is skipped

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 785

copy 2007 Pearson Addison-Wesley All rights reserved 5-7

Logic of an if statement

condition

evaluated

statement

true false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 885

copy 2007 Pearson Addison-Wesley All rights reserved 5-8

Boolean Expressions

bull A condition often uses one of Javas equality operators or relational operators which all returnboolean results

== equal to= not equal to

lt less thangt greater than

lt= less than or equal to

gt= greater than or equal to

bull Note the difference between the equality operator(== ) and the assignment operator ( =)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 985

copy 2007 Pearson Addison-Wesley All rights reserved 5-9

The if Statement

bull An example of an if statementif (sum gt MAX)

delta = sum - MAXSystemoutprintln (The sum is + sum)

bull First the condition is evaluated -- the value of sum is either greater than the value of MAX or it is not

bull If the condition is true the assignment statement

is executed -- if it isnrsquot it is skipped bull Either way the call to println is executed next

bull See Agejava (page 216)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1085

copy 2007 Pearson Addison-Wesley All rights reserved 5-10

Indentation

bull The statement controlled by the if statement isindented to indicate that relationship

bull The use of a consistent indentation style makes a

program easier to read and understandbull Although it makes no difference to the compiler

proper indentation is crucialAlways code so the person who ends upmaintaining your code can figure it outwithout talking to you after you have left thejob

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1185

copy 2007 Pearson Addison-Wesley All rights reserved 5-11

The if Statement

bull What do the following statements doif (top gt= MAXIMUM)

top = 0

Sets top to zero if the current value of top is greaterthan or equal to the value of MAXIMUM

if (total = stock + warehouse)inventoryError = true

Sets a flag to true if the value of total is not equal to

the sum of stock and warehouse bull The precedence of the arithmetic operators is

higher than the precedence of the equality andrelational operators

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1285

copy 2007 Pearson Addison-Wesley All rights reserved 5-12

Logical Operators

bull Boolean expressions can also use the followinglogical operators

Logical NOTampamp Logical AND

|| Logical ORbull They all take boolean operands and produce

boolean results

bull

Logical NOT is a unary operator (it operates onone operand)

bull Logical AND and logical OR are binary operators(each operates on two operands)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1385

copy 2007 Pearson Addison-Wesley All rights reserved 5-13

Logical NOT

bull The logical NOT operation is also called logical negation or logical complement

bull If some boolean condition a is true then a isfalse if a is false then a is true

bull Logical expressions can be shown using a truth table

a atrue false

false true

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1485

copy 2007 Pearson Addison-Wesley All rights reserved 5-14

Logical AND and Logical OR

bull The logical AND expression

a ampamp b

is true if both a and b are true and false otherwise

bull The logical OR expression

a || b

is true if a or b or both are true and falseotherwise

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1585

copy 2007 Pearson Addison-Wesley All rights reserved 5-15

Logical Operators

bull Expressions that use logical operators can formcomplex conditions

if (total lt MAX+5 ampamp found)Systemoutprintln (Processinghellip)

bull All logical operators have lower precedence thanthe relational operators

bull Logical NOT has higher precedence than logicalAND and logical OR

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 2: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 285

copy 2007 Pearson Addison-Wesley All rights reserved 5-2

Conditionals and Loops

bull Now we will examine programming statements thatallow us to

make decisionsrepeat processing steps in a loop

bull Chapter 5 focuses on

boolean expressionsconditional statements

comparing datarepetition statementsiteratorsmore drawing techniquesmore GUI components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 385

copy 2007 Pearson Addison-Wesley All rights reserved 5-3

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing DataThe while Statement

Iterators

Other Repetition StatementsDecisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 485

copy 2007 Pearson Addison-Wesley All rights reserved 5-4

Flow of Control

bull Unless specified otherwise the order of statementexecution through a method is linear onestatement after another in sequence

bull Some programming statements allow us todecide whether or not to execute a particular statementexecute a statement over and over repetitively

bull These decisions are based on boolean expressions

(or conditions ) that evaluate to true or falsebull The order of statement execution is called the flow

of control

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 585

copy 2007 Pearson Addison-Wesley All rights reserved 5-5

Conditional Statements

bull A conditional statement lets us choose whichstatement will be executed next

bull Therefore they are sometimes called selection

statements bull Conditional statements give us the power to

make basic decisions

bull

The Java conditional statements are theif statement if-else statement switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 685

copy 2007 Pearson Addison-Wesley All rights reserved 5-6

The if Statement

bull The if statement has the following syntax

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 executedIf it is false the statement is skipped

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 785

copy 2007 Pearson Addison-Wesley All rights reserved 5-7

Logic of an if statement

condition

evaluated

statement

true false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 885

copy 2007 Pearson Addison-Wesley All rights reserved 5-8

Boolean Expressions

bull A condition often uses one of Javas equality operators or relational operators which all returnboolean results

== equal to= not equal to

lt less thangt greater than

lt= less than or equal to

gt= greater than or equal to

bull Note the difference between the equality operator(== ) and the assignment operator ( =)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 985

copy 2007 Pearson Addison-Wesley All rights reserved 5-9

The if Statement

bull An example of an if statementif (sum gt MAX)

delta = sum - MAXSystemoutprintln (The sum is + sum)

bull First the condition is evaluated -- the value of sum is either greater than the value of MAX or it is not

bull If the condition is true the assignment statement

is executed -- if it isnrsquot it is skipped bull Either way the call to println is executed next

bull See Agejava (page 216)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1085

copy 2007 Pearson Addison-Wesley All rights reserved 5-10

Indentation

bull The statement controlled by the if statement isindented to indicate that relationship

bull The use of a consistent indentation style makes a

program easier to read and understandbull Although it makes no difference to the compiler

proper indentation is crucialAlways code so the person who ends upmaintaining your code can figure it outwithout talking to you after you have left thejob

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1185

copy 2007 Pearson Addison-Wesley All rights reserved 5-11

The if Statement

bull What do the following statements doif (top gt= MAXIMUM)

top = 0

Sets top to zero if the current value of top is greaterthan or equal to the value of MAXIMUM

if (total = stock + warehouse)inventoryError = true

Sets a flag to true if the value of total is not equal to

the sum of stock and warehouse bull The precedence of the arithmetic operators is

higher than the precedence of the equality andrelational operators

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1285

copy 2007 Pearson Addison-Wesley All rights reserved 5-12

Logical Operators

bull Boolean expressions can also use the followinglogical operators

Logical NOTampamp Logical AND

|| Logical ORbull They all take boolean operands and produce

boolean results

bull

Logical NOT is a unary operator (it operates onone operand)

bull Logical AND and logical OR are binary operators(each operates on two operands)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1385

copy 2007 Pearson Addison-Wesley All rights reserved 5-13

Logical NOT

bull The logical NOT operation is also called logical negation or logical complement

bull If some boolean condition a is true then a isfalse if a is false then a is true

bull Logical expressions can be shown using a truth table

a atrue false

false true

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1485

copy 2007 Pearson Addison-Wesley All rights reserved 5-14

Logical AND and Logical OR

bull The logical AND expression

a ampamp b

is true if both a and b are true and false otherwise

bull The logical OR expression

a || b

is true if a or b or both are true and falseotherwise

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1585

copy 2007 Pearson Addison-Wesley All rights reserved 5-15

Logical Operators

bull Expressions that use logical operators can formcomplex conditions

if (total lt MAX+5 ampamp found)Systemoutprintln (Processinghellip)

bull All logical operators have lower precedence thanthe relational operators

bull Logical NOT has higher precedence than logicalAND and logical OR

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 3: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 385

copy 2007 Pearson Addison-Wesley All rights reserved 5-3

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing DataThe while Statement

Iterators

Other Repetition StatementsDecisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 485

copy 2007 Pearson Addison-Wesley All rights reserved 5-4

Flow of Control

bull Unless specified otherwise the order of statementexecution through a method is linear onestatement after another in sequence

bull Some programming statements allow us todecide whether or not to execute a particular statementexecute a statement over and over repetitively

bull These decisions are based on boolean expressions

(or conditions ) that evaluate to true or falsebull The order of statement execution is called the flow

of control

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 585

copy 2007 Pearson Addison-Wesley All rights reserved 5-5

Conditional Statements

bull A conditional statement lets us choose whichstatement will be executed next

bull Therefore they are sometimes called selection

statements bull Conditional statements give us the power to

make basic decisions

bull

The Java conditional statements are theif statement if-else statement switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 685

copy 2007 Pearson Addison-Wesley All rights reserved 5-6

The if Statement

bull The if statement has the following syntax

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 executedIf it is false the statement is skipped

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 785

copy 2007 Pearson Addison-Wesley All rights reserved 5-7

Logic of an if statement

condition

evaluated

statement

true false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 885

copy 2007 Pearson Addison-Wesley All rights reserved 5-8

Boolean Expressions

bull A condition often uses one of Javas equality operators or relational operators which all returnboolean results

== equal to= not equal to

lt less thangt greater than

lt= less than or equal to

gt= greater than or equal to

bull Note the difference between the equality operator(== ) and the assignment operator ( =)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 985

copy 2007 Pearson Addison-Wesley All rights reserved 5-9

The if Statement

bull An example of an if statementif (sum gt MAX)

delta = sum - MAXSystemoutprintln (The sum is + sum)

bull First the condition is evaluated -- the value of sum is either greater than the value of MAX or it is not

bull If the condition is true the assignment statement

is executed -- if it isnrsquot it is skipped bull Either way the call to println is executed next

bull See Agejava (page 216)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1085

copy 2007 Pearson Addison-Wesley All rights reserved 5-10

Indentation

bull The statement controlled by the if statement isindented to indicate that relationship

bull The use of a consistent indentation style makes a

program easier to read and understandbull Although it makes no difference to the compiler

proper indentation is crucialAlways code so the person who ends upmaintaining your code can figure it outwithout talking to you after you have left thejob

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1185

copy 2007 Pearson Addison-Wesley All rights reserved 5-11

The if Statement

bull What do the following statements doif (top gt= MAXIMUM)

top = 0

Sets top to zero if the current value of top is greaterthan or equal to the value of MAXIMUM

if (total = stock + warehouse)inventoryError = true

Sets a flag to true if the value of total is not equal to

the sum of stock and warehouse bull The precedence of the arithmetic operators is

higher than the precedence of the equality andrelational operators

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1285

copy 2007 Pearson Addison-Wesley All rights reserved 5-12

Logical Operators

bull Boolean expressions can also use the followinglogical operators

Logical NOTampamp Logical AND

|| Logical ORbull They all take boolean operands and produce

boolean results

bull

Logical NOT is a unary operator (it operates onone operand)

bull Logical AND and logical OR are binary operators(each operates on two operands)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1385

copy 2007 Pearson Addison-Wesley All rights reserved 5-13

Logical NOT

bull The logical NOT operation is also called logical negation or logical complement

bull If some boolean condition a is true then a isfalse if a is false then a is true

bull Logical expressions can be shown using a truth table

a atrue false

false true

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1485

copy 2007 Pearson Addison-Wesley All rights reserved 5-14

Logical AND and Logical OR

bull The logical AND expression

a ampamp b

is true if both a and b are true and false otherwise

bull The logical OR expression

a || b

is true if a or b or both are true and falseotherwise

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1585

copy 2007 Pearson Addison-Wesley All rights reserved 5-15

Logical Operators

bull Expressions that use logical operators can formcomplex conditions

if (total lt MAX+5 ampamp found)Systemoutprintln (Processinghellip)

bull All logical operators have lower precedence thanthe relational operators

bull Logical NOT has higher precedence than logicalAND and logical OR

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 4: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 485

copy 2007 Pearson Addison-Wesley All rights reserved 5-4

Flow of Control

bull Unless specified otherwise the order of statementexecution through a method is linear onestatement after another in sequence

bull Some programming statements allow us todecide whether or not to execute a particular statementexecute a statement over and over repetitively

bull These decisions are based on boolean expressions

(or conditions ) that evaluate to true or falsebull The order of statement execution is called the flow

of control

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 585

copy 2007 Pearson Addison-Wesley All rights reserved 5-5

Conditional Statements

bull A conditional statement lets us choose whichstatement will be executed next

bull Therefore they are sometimes called selection

statements bull Conditional statements give us the power to

make basic decisions

bull

The Java conditional statements are theif statement if-else statement switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 685

copy 2007 Pearson Addison-Wesley All rights reserved 5-6

The if Statement

bull The if statement has the following syntax

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 executedIf it is false the statement is skipped

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 785

copy 2007 Pearson Addison-Wesley All rights reserved 5-7

Logic of an if statement

condition

evaluated

statement

true false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 885

copy 2007 Pearson Addison-Wesley All rights reserved 5-8

Boolean Expressions

bull A condition often uses one of Javas equality operators or relational operators which all returnboolean results

== equal to= not equal to

lt less thangt greater than

lt= less than or equal to

gt= greater than or equal to

bull Note the difference between the equality operator(== ) and the assignment operator ( =)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 985

copy 2007 Pearson Addison-Wesley All rights reserved 5-9

The if Statement

bull An example of an if statementif (sum gt MAX)

delta = sum - MAXSystemoutprintln (The sum is + sum)

bull First the condition is evaluated -- the value of sum is either greater than the value of MAX or it is not

bull If the condition is true the assignment statement

is executed -- if it isnrsquot it is skipped bull Either way the call to println is executed next

bull See Agejava (page 216)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1085

copy 2007 Pearson Addison-Wesley All rights reserved 5-10

Indentation

bull The statement controlled by the if statement isindented to indicate that relationship

bull The use of a consistent indentation style makes a

program easier to read and understandbull Although it makes no difference to the compiler

proper indentation is crucialAlways code so the person who ends upmaintaining your code can figure it outwithout talking to you after you have left thejob

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1185

copy 2007 Pearson Addison-Wesley All rights reserved 5-11

The if Statement

bull What do the following statements doif (top gt= MAXIMUM)

top = 0

Sets top to zero if the current value of top is greaterthan or equal to the value of MAXIMUM

if (total = stock + warehouse)inventoryError = true

Sets a flag to true if the value of total is not equal to

the sum of stock and warehouse bull The precedence of the arithmetic operators is

higher than the precedence of the equality andrelational operators

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1285

copy 2007 Pearson Addison-Wesley All rights reserved 5-12

Logical Operators

bull Boolean expressions can also use the followinglogical operators

Logical NOTampamp Logical AND

|| Logical ORbull They all take boolean operands and produce

boolean results

bull

Logical NOT is a unary operator (it operates onone operand)

bull Logical AND and logical OR are binary operators(each operates on two operands)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1385

copy 2007 Pearson Addison-Wesley All rights reserved 5-13

Logical NOT

bull The logical NOT operation is also called logical negation or logical complement

bull If some boolean condition a is true then a isfalse if a is false then a is true

bull Logical expressions can be shown using a truth table

a atrue false

false true

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1485

copy 2007 Pearson Addison-Wesley All rights reserved 5-14

Logical AND and Logical OR

bull The logical AND expression

a ampamp b

is true if both a and b are true and false otherwise

bull The logical OR expression

a || b

is true if a or b or both are true and falseotherwise

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1585

copy 2007 Pearson Addison-Wesley All rights reserved 5-15

Logical Operators

bull Expressions that use logical operators can formcomplex conditions

if (total lt MAX+5 ampamp found)Systemoutprintln (Processinghellip)

bull All logical operators have lower precedence thanthe relational operators

bull Logical NOT has higher precedence than logicalAND and logical OR

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 5: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 585

copy 2007 Pearson Addison-Wesley All rights reserved 5-5

Conditional Statements

bull A conditional statement lets us choose whichstatement will be executed next

bull Therefore they are sometimes called selection

statements bull Conditional statements give us the power to

make basic decisions

bull

The Java conditional statements are theif statement if-else statement switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 685

copy 2007 Pearson Addison-Wesley All rights reserved 5-6

The if Statement

bull The if statement has the following syntax

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 executedIf it is false the statement is skipped

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 785

copy 2007 Pearson Addison-Wesley All rights reserved 5-7

Logic of an if statement

condition

evaluated

statement

true false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 885

copy 2007 Pearson Addison-Wesley All rights reserved 5-8

Boolean Expressions

bull A condition often uses one of Javas equality operators or relational operators which all returnboolean results

== equal to= not equal to

lt less thangt greater than

lt= less than or equal to

gt= greater than or equal to

bull Note the difference between the equality operator(== ) and the assignment operator ( =)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 985

copy 2007 Pearson Addison-Wesley All rights reserved 5-9

The if Statement

bull An example of an if statementif (sum gt MAX)

delta = sum - MAXSystemoutprintln (The sum is + sum)

bull First the condition is evaluated -- the value of sum is either greater than the value of MAX or it is not

bull If the condition is true the assignment statement

is executed -- if it isnrsquot it is skipped bull Either way the call to println is executed next

bull See Agejava (page 216)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1085

copy 2007 Pearson Addison-Wesley All rights reserved 5-10

Indentation

bull The statement controlled by the if statement isindented to indicate that relationship

bull The use of a consistent indentation style makes a

program easier to read and understandbull Although it makes no difference to the compiler

proper indentation is crucialAlways code so the person who ends upmaintaining your code can figure it outwithout talking to you after you have left thejob

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1185

copy 2007 Pearson Addison-Wesley All rights reserved 5-11

The if Statement

bull What do the following statements doif (top gt= MAXIMUM)

top = 0

Sets top to zero if the current value of top is greaterthan or equal to the value of MAXIMUM

if (total = stock + warehouse)inventoryError = true

Sets a flag to true if the value of total is not equal to

the sum of stock and warehouse bull The precedence of the arithmetic operators is

higher than the precedence of the equality andrelational operators

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1285

copy 2007 Pearson Addison-Wesley All rights reserved 5-12

Logical Operators

bull Boolean expressions can also use the followinglogical operators

Logical NOTampamp Logical AND

|| Logical ORbull They all take boolean operands and produce

boolean results

bull

Logical NOT is a unary operator (it operates onone operand)

bull Logical AND and logical OR are binary operators(each operates on two operands)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1385

copy 2007 Pearson Addison-Wesley All rights reserved 5-13

Logical NOT

bull The logical NOT operation is also called logical negation or logical complement

bull If some boolean condition a is true then a isfalse if a is false then a is true

bull Logical expressions can be shown using a truth table

a atrue false

false true

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1485

copy 2007 Pearson Addison-Wesley All rights reserved 5-14

Logical AND and Logical OR

bull The logical AND expression

a ampamp b

is true if both a and b are true and false otherwise

bull The logical OR expression

a || b

is true if a or b or both are true and falseotherwise

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1585

copy 2007 Pearson Addison-Wesley All rights reserved 5-15

Logical Operators

bull Expressions that use logical operators can formcomplex conditions

if (total lt MAX+5 ampamp found)Systemoutprintln (Processinghellip)

bull All logical operators have lower precedence thanthe relational operators

bull Logical NOT has higher precedence than logicalAND and logical OR

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 6: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 685

copy 2007 Pearson Addison-Wesley All rights reserved 5-6

The if Statement

bull The if statement has the following syntax

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 executedIf it is false the statement is skipped

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 785

copy 2007 Pearson Addison-Wesley All rights reserved 5-7

Logic of an if statement

condition

evaluated

statement

true false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 885

copy 2007 Pearson Addison-Wesley All rights reserved 5-8

Boolean Expressions

bull A condition often uses one of Javas equality operators or relational operators which all returnboolean results

== equal to= not equal to

lt less thangt greater than

lt= less than or equal to

gt= greater than or equal to

bull Note the difference between the equality operator(== ) and the assignment operator ( =)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 985

copy 2007 Pearson Addison-Wesley All rights reserved 5-9

The if Statement

bull An example of an if statementif (sum gt MAX)

delta = sum - MAXSystemoutprintln (The sum is + sum)

bull First the condition is evaluated -- the value of sum is either greater than the value of MAX or it is not

bull If the condition is true the assignment statement

is executed -- if it isnrsquot it is skipped bull Either way the call to println is executed next

bull See Agejava (page 216)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1085

copy 2007 Pearson Addison-Wesley All rights reserved 5-10

Indentation

bull The statement controlled by the if statement isindented to indicate that relationship

bull The use of a consistent indentation style makes a

program easier to read and understandbull Although it makes no difference to the compiler

proper indentation is crucialAlways code so the person who ends upmaintaining your code can figure it outwithout talking to you after you have left thejob

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1185

copy 2007 Pearson Addison-Wesley All rights reserved 5-11

The if Statement

bull What do the following statements doif (top gt= MAXIMUM)

top = 0

Sets top to zero if the current value of top is greaterthan or equal to the value of MAXIMUM

if (total = stock + warehouse)inventoryError = true

Sets a flag to true if the value of total is not equal to

the sum of stock and warehouse bull The precedence of the arithmetic operators is

higher than the precedence of the equality andrelational operators

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1285

copy 2007 Pearson Addison-Wesley All rights reserved 5-12

Logical Operators

bull Boolean expressions can also use the followinglogical operators

Logical NOTampamp Logical AND

|| Logical ORbull They all take boolean operands and produce

boolean results

bull

Logical NOT is a unary operator (it operates onone operand)

bull Logical AND and logical OR are binary operators(each operates on two operands)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1385

copy 2007 Pearson Addison-Wesley All rights reserved 5-13

Logical NOT

bull The logical NOT operation is also called logical negation or logical complement

bull If some boolean condition a is true then a isfalse if a is false then a is true

bull Logical expressions can be shown using a truth table

a atrue false

false true

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1485

copy 2007 Pearson Addison-Wesley All rights reserved 5-14

Logical AND and Logical OR

bull The logical AND expression

a ampamp b

is true if both a and b are true and false otherwise

bull The logical OR expression

a || b

is true if a or b or both are true and falseotherwise

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1585

copy 2007 Pearson Addison-Wesley All rights reserved 5-15

Logical Operators

bull Expressions that use logical operators can formcomplex conditions

if (total lt MAX+5 ampamp found)Systemoutprintln (Processinghellip)

bull All logical operators have lower precedence thanthe relational operators

bull Logical NOT has higher precedence than logicalAND and logical OR

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 7: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 785

copy 2007 Pearson Addison-Wesley All rights reserved 5-7

Logic of an if statement

condition

evaluated

statement

true false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 885

copy 2007 Pearson Addison-Wesley All rights reserved 5-8

Boolean Expressions

bull A condition often uses one of Javas equality operators or relational operators which all returnboolean results

== equal to= not equal to

lt less thangt greater than

lt= less than or equal to

gt= greater than or equal to

bull Note the difference between the equality operator(== ) and the assignment operator ( =)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 985

copy 2007 Pearson Addison-Wesley All rights reserved 5-9

The if Statement

bull An example of an if statementif (sum gt MAX)

delta = sum - MAXSystemoutprintln (The sum is + sum)

bull First the condition is evaluated -- the value of sum is either greater than the value of MAX or it is not

bull If the condition is true the assignment statement

is executed -- if it isnrsquot it is skipped bull Either way the call to println is executed next

bull See Agejava (page 216)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1085

copy 2007 Pearson Addison-Wesley All rights reserved 5-10

Indentation

bull The statement controlled by the if statement isindented to indicate that relationship

bull The use of a consistent indentation style makes a

program easier to read and understandbull Although it makes no difference to the compiler

proper indentation is crucialAlways code so the person who ends upmaintaining your code can figure it outwithout talking to you after you have left thejob

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1185

copy 2007 Pearson Addison-Wesley All rights reserved 5-11

The if Statement

bull What do the following statements doif (top gt= MAXIMUM)

top = 0

Sets top to zero if the current value of top is greaterthan or equal to the value of MAXIMUM

if (total = stock + warehouse)inventoryError = true

Sets a flag to true if the value of total is not equal to

the sum of stock and warehouse bull The precedence of the arithmetic operators is

higher than the precedence of the equality andrelational operators

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1285

copy 2007 Pearson Addison-Wesley All rights reserved 5-12

Logical Operators

bull Boolean expressions can also use the followinglogical operators

Logical NOTampamp Logical AND

|| Logical ORbull They all take boolean operands and produce

boolean results

bull

Logical NOT is a unary operator (it operates onone operand)

bull Logical AND and logical OR are binary operators(each operates on two operands)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1385

copy 2007 Pearson Addison-Wesley All rights reserved 5-13

Logical NOT

bull The logical NOT operation is also called logical negation or logical complement

bull If some boolean condition a is true then a isfalse if a is false then a is true

bull Logical expressions can be shown using a truth table

a atrue false

false true

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1485

copy 2007 Pearson Addison-Wesley All rights reserved 5-14

Logical AND and Logical OR

bull The logical AND expression

a ampamp b

is true if both a and b are true and false otherwise

bull The logical OR expression

a || b

is true if a or b or both are true and falseotherwise

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1585

copy 2007 Pearson Addison-Wesley All rights reserved 5-15

Logical Operators

bull Expressions that use logical operators can formcomplex conditions

if (total lt MAX+5 ampamp found)Systemoutprintln (Processinghellip)

bull All logical operators have lower precedence thanthe relational operators

bull Logical NOT has higher precedence than logicalAND and logical OR

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 8: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 885

copy 2007 Pearson Addison-Wesley All rights reserved 5-8

Boolean Expressions

bull A condition often uses one of Javas equality operators or relational operators which all returnboolean results

== equal to= not equal to

lt less thangt greater than

lt= less than or equal to

gt= greater than or equal to

bull Note the difference between the equality operator(== ) and the assignment operator ( =)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 985

copy 2007 Pearson Addison-Wesley All rights reserved 5-9

The if Statement

bull An example of an if statementif (sum gt MAX)

delta = sum - MAXSystemoutprintln (The sum is + sum)

bull First the condition is evaluated -- the value of sum is either greater than the value of MAX or it is not

bull If the condition is true the assignment statement

is executed -- if it isnrsquot it is skipped bull Either way the call to println is executed next

bull See Agejava (page 216)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1085

copy 2007 Pearson Addison-Wesley All rights reserved 5-10

Indentation

bull The statement controlled by the if statement isindented to indicate that relationship

bull The use of a consistent indentation style makes a

program easier to read and understandbull Although it makes no difference to the compiler

proper indentation is crucialAlways code so the person who ends upmaintaining your code can figure it outwithout talking to you after you have left thejob

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1185

copy 2007 Pearson Addison-Wesley All rights reserved 5-11

The if Statement

bull What do the following statements doif (top gt= MAXIMUM)

top = 0

Sets top to zero if the current value of top is greaterthan or equal to the value of MAXIMUM

if (total = stock + warehouse)inventoryError = true

Sets a flag to true if the value of total is not equal to

the sum of stock and warehouse bull The precedence of the arithmetic operators is

higher than the precedence of the equality andrelational operators

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1285

copy 2007 Pearson Addison-Wesley All rights reserved 5-12

Logical Operators

bull Boolean expressions can also use the followinglogical operators

Logical NOTampamp Logical AND

|| Logical ORbull They all take boolean operands and produce

boolean results

bull

Logical NOT is a unary operator (it operates onone operand)

bull Logical AND and logical OR are binary operators(each operates on two operands)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1385

copy 2007 Pearson Addison-Wesley All rights reserved 5-13

Logical NOT

bull The logical NOT operation is also called logical negation or logical complement

bull If some boolean condition a is true then a isfalse if a is false then a is true

bull Logical expressions can be shown using a truth table

a atrue false

false true

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1485

copy 2007 Pearson Addison-Wesley All rights reserved 5-14

Logical AND and Logical OR

bull The logical AND expression

a ampamp b

is true if both a and b are true and false otherwise

bull The logical OR expression

a || b

is true if a or b or both are true and falseotherwise

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1585

copy 2007 Pearson Addison-Wesley All rights reserved 5-15

Logical Operators

bull Expressions that use logical operators can formcomplex conditions

if (total lt MAX+5 ampamp found)Systemoutprintln (Processinghellip)

bull All logical operators have lower precedence thanthe relational operators

bull Logical NOT has higher precedence than logicalAND and logical OR

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 9: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 985

copy 2007 Pearson Addison-Wesley All rights reserved 5-9

The if Statement

bull An example of an if statementif (sum gt MAX)

delta = sum - MAXSystemoutprintln (The sum is + sum)

bull First the condition is evaluated -- the value of sum is either greater than the value of MAX or it is not

bull If the condition is true the assignment statement

is executed -- if it isnrsquot it is skipped bull Either way the call to println is executed next

bull See Agejava (page 216)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1085

copy 2007 Pearson Addison-Wesley All rights reserved 5-10

Indentation

bull The statement controlled by the if statement isindented to indicate that relationship

bull The use of a consistent indentation style makes a

program easier to read and understandbull Although it makes no difference to the compiler

proper indentation is crucialAlways code so the person who ends upmaintaining your code can figure it outwithout talking to you after you have left thejob

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1185

copy 2007 Pearson Addison-Wesley All rights reserved 5-11

The if Statement

bull What do the following statements doif (top gt= MAXIMUM)

top = 0

Sets top to zero if the current value of top is greaterthan or equal to the value of MAXIMUM

if (total = stock + warehouse)inventoryError = true

Sets a flag to true if the value of total is not equal to

the sum of stock and warehouse bull The precedence of the arithmetic operators is

higher than the precedence of the equality andrelational operators

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1285

copy 2007 Pearson Addison-Wesley All rights reserved 5-12

Logical Operators

bull Boolean expressions can also use the followinglogical operators

Logical NOTampamp Logical AND

|| Logical ORbull They all take boolean operands and produce

boolean results

bull

Logical NOT is a unary operator (it operates onone operand)

bull Logical AND and logical OR are binary operators(each operates on two operands)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1385

copy 2007 Pearson Addison-Wesley All rights reserved 5-13

Logical NOT

bull The logical NOT operation is also called logical negation or logical complement

bull If some boolean condition a is true then a isfalse if a is false then a is true

bull Logical expressions can be shown using a truth table

a atrue false

false true

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1485

copy 2007 Pearson Addison-Wesley All rights reserved 5-14

Logical AND and Logical OR

bull The logical AND expression

a ampamp b

is true if both a and b are true and false otherwise

bull The logical OR expression

a || b

is true if a or b or both are true and falseotherwise

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1585

copy 2007 Pearson Addison-Wesley All rights reserved 5-15

Logical Operators

bull Expressions that use logical operators can formcomplex conditions

if (total lt MAX+5 ampamp found)Systemoutprintln (Processinghellip)

bull All logical operators have lower precedence thanthe relational operators

bull Logical NOT has higher precedence than logicalAND and logical OR

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 10: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1085

copy 2007 Pearson Addison-Wesley All rights reserved 5-10

Indentation

bull The statement controlled by the if statement isindented to indicate that relationship

bull The use of a consistent indentation style makes a

program easier to read and understandbull Although it makes no difference to the compiler

proper indentation is crucialAlways code so the person who ends upmaintaining your code can figure it outwithout talking to you after you have left thejob

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1185

copy 2007 Pearson Addison-Wesley All rights reserved 5-11

The if Statement

bull What do the following statements doif (top gt= MAXIMUM)

top = 0

Sets top to zero if the current value of top is greaterthan or equal to the value of MAXIMUM

if (total = stock + warehouse)inventoryError = true

Sets a flag to true if the value of total is not equal to

the sum of stock and warehouse bull The precedence of the arithmetic operators is

higher than the precedence of the equality andrelational operators

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1285

copy 2007 Pearson Addison-Wesley All rights reserved 5-12

Logical Operators

bull Boolean expressions can also use the followinglogical operators

Logical NOTampamp Logical AND

|| Logical ORbull They all take boolean operands and produce

boolean results

bull

Logical NOT is a unary operator (it operates onone operand)

bull Logical AND and logical OR are binary operators(each operates on two operands)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1385

copy 2007 Pearson Addison-Wesley All rights reserved 5-13

Logical NOT

bull The logical NOT operation is also called logical negation or logical complement

bull If some boolean condition a is true then a isfalse if a is false then a is true

bull Logical expressions can be shown using a truth table

a atrue false

false true

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1485

copy 2007 Pearson Addison-Wesley All rights reserved 5-14

Logical AND and Logical OR

bull The logical AND expression

a ampamp b

is true if both a and b are true and false otherwise

bull The logical OR expression

a || b

is true if a or b or both are true and falseotherwise

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1585

copy 2007 Pearson Addison-Wesley All rights reserved 5-15

Logical Operators

bull Expressions that use logical operators can formcomplex conditions

if (total lt MAX+5 ampamp found)Systemoutprintln (Processinghellip)

bull All logical operators have lower precedence thanthe relational operators

bull Logical NOT has higher precedence than logicalAND and logical OR

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 11: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1185

copy 2007 Pearson Addison-Wesley All rights reserved 5-11

The if Statement

bull What do the following statements doif (top gt= MAXIMUM)

top = 0

Sets top to zero if the current value of top is greaterthan or equal to the value of MAXIMUM

if (total = stock + warehouse)inventoryError = true

Sets a flag to true if the value of total is not equal to

the sum of stock and warehouse bull The precedence of the arithmetic operators is

higher than the precedence of the equality andrelational operators

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1285

copy 2007 Pearson Addison-Wesley All rights reserved 5-12

Logical Operators

bull Boolean expressions can also use the followinglogical operators

Logical NOTampamp Logical AND

|| Logical ORbull They all take boolean operands and produce

boolean results

bull

Logical NOT is a unary operator (it operates onone operand)

bull Logical AND and logical OR are binary operators(each operates on two operands)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1385

copy 2007 Pearson Addison-Wesley All rights reserved 5-13

Logical NOT

bull The logical NOT operation is also called logical negation or logical complement

bull If some boolean condition a is true then a isfalse if a is false then a is true

bull Logical expressions can be shown using a truth table

a atrue false

false true

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1485

copy 2007 Pearson Addison-Wesley All rights reserved 5-14

Logical AND and Logical OR

bull The logical AND expression

a ampamp b

is true if both a and b are true and false otherwise

bull The logical OR expression

a || b

is true if a or b or both are true and falseotherwise

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1585

copy 2007 Pearson Addison-Wesley All rights reserved 5-15

Logical Operators

bull Expressions that use logical operators can formcomplex conditions

if (total lt MAX+5 ampamp found)Systemoutprintln (Processinghellip)

bull All logical operators have lower precedence thanthe relational operators

bull Logical NOT has higher precedence than logicalAND and logical OR

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 12: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1285

copy 2007 Pearson Addison-Wesley All rights reserved 5-12

Logical Operators

bull Boolean expressions can also use the followinglogical operators

Logical NOTampamp Logical AND

|| Logical ORbull They all take boolean operands and produce

boolean results

bull

Logical NOT is a unary operator (it operates onone operand)

bull Logical AND and logical OR are binary operators(each operates on two operands)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1385

copy 2007 Pearson Addison-Wesley All rights reserved 5-13

Logical NOT

bull The logical NOT operation is also called logical negation or logical complement

bull If some boolean condition a is true then a isfalse if a is false then a is true

bull Logical expressions can be shown using a truth table

a atrue false

false true

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1485

copy 2007 Pearson Addison-Wesley All rights reserved 5-14

Logical AND and Logical OR

bull The logical AND expression

a ampamp b

is true if both a and b are true and false otherwise

bull The logical OR expression

a || b

is true if a or b or both are true and falseotherwise

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1585

copy 2007 Pearson Addison-Wesley All rights reserved 5-15

Logical Operators

bull Expressions that use logical operators can formcomplex conditions

if (total lt MAX+5 ampamp found)Systemoutprintln (Processinghellip)

bull All logical operators have lower precedence thanthe relational operators

bull Logical NOT has higher precedence than logicalAND and logical OR

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 13: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1385

copy 2007 Pearson Addison-Wesley All rights reserved 5-13

Logical NOT

bull The logical NOT operation is also called logical negation or logical complement

bull If some boolean condition a is true then a isfalse if a is false then a is true

bull Logical expressions can be shown using a truth table

a atrue false

false true

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1485

copy 2007 Pearson Addison-Wesley All rights reserved 5-14

Logical AND and Logical OR

bull The logical AND expression

a ampamp b

is true if both a and b are true and false otherwise

bull The logical OR expression

a || b

is true if a or b or both are true and falseotherwise

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1585

copy 2007 Pearson Addison-Wesley All rights reserved 5-15

Logical Operators

bull Expressions that use logical operators can formcomplex conditions

if (total lt MAX+5 ampamp found)Systemoutprintln (Processinghellip)

bull All logical operators have lower precedence thanthe relational operators

bull Logical NOT has higher precedence than logicalAND and logical OR

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 14: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1485

copy 2007 Pearson Addison-Wesley All rights reserved 5-14

Logical AND and Logical OR

bull The logical AND expression

a ampamp b

is true if both a and b are true and false otherwise

bull The logical OR expression

a || b

is true if a or b or both are true and falseotherwise

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1585

copy 2007 Pearson Addison-Wesley All rights reserved 5-15

Logical Operators

bull Expressions that use logical operators can formcomplex conditions

if (total lt MAX+5 ampamp found)Systemoutprintln (Processinghellip)

bull All logical operators have lower precedence thanthe relational operators

bull Logical NOT has higher precedence than logicalAND and logical OR

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 15: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1585

copy 2007 Pearson Addison-Wesley All rights reserved 5-15

Logical Operators

bull Expressions that use logical operators can formcomplex conditions

if (total lt MAX+5 ampamp found)Systemoutprintln (Processinghellip)

bull All logical operators have lower precedence thanthe relational operators

bull Logical NOT has higher precedence than logicalAND and logical OR

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 16: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1685

copy 2007 Pearson Addison-Wesley All rights reserved 5-16

Logical Operators

bull A truth table shows all possible true-falsecombinations of the terms

bull Since ampampand || each have two operands thereare four possible combinations of conditions a and b

a b a ampamp b a || b

true true true true

true false false true

false true false true

false false false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 17: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1785

copy 2007 Pearson Addison-Wesley All rights reserved 5-17

Boolean Expressions

bull Specific expressions can be evaluated using truthtables

total lt MAX found found total lt MAX ampamp found

false false true false

false true false false

true false true true

true true false false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 18: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1885

copy 2007 Pearson Addison-Wesley All rights reserved 5-18

Short-Circuited Operatorsbull The processing of logical AND and logical OR is

ldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine theresult the right operand is not evaluated

bull As shown above you can use short-circuiting toavoid errors

bull

This type of processing must be used carefully oryou can get errors as shown below the checkingmust be done on the left

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (totalcount gt MAX ampamp count = 0)Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 19: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 1985

copy 2007 Pearson Addison-Wesley All rights reserved 5-19

Short-Circuited Operators

bull The processing of logical AND and logical OR isldquoshort -circuitedrdquo

bull If the left operand is sufficient to determine the

result the right operand is not evaluated

bull

This is equivalent to

if (count = 0 ampamp totalcount gt MAX)Systemoutprintln (Testinghellip)

if (count = 0) if (totalcount gt MAX)

Systemoutprintln (Testinghellip)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 20: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2085

copy 2007 Pearson Addison-Wesley All rights reserved 5-20

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 21: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2185

copy 2007 Pearson Addison-Wesley All rights reserved 5-21

The if-else Statement

bull An else clause can be added to an if statement tomake an if-else statement

if ( condition )statement1

elsestatement2

bull If the condition is true statement1 is executedif the condition is false statement2 is executed

bull One or the other will be executed but not both

bull See Wagesjava (page 219)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 22: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2285

copy 2007 Pearson Addison-Wesley All rights reserved 5-22

Logic of an if-else statement

condition

evaluated

statement1

true false

statement2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 23: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2385

copy 2007 Pearson Addison-Wesley All rights reserved 5-23

The Coin Class

bull Lets examine a class that represents a coin thatcan be flipped

bull Instance data is used to indicate which face (heads

or tails) is currently showingbull See CoinFlipjava (page 220)bull See Coinjava (page 221)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 24: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2485

copy 2007 Pearson Addison-Wesley All rights reserved 5-24

Indentation Revisited

bull Remember that indentation is for the humanreader and is ignored by the computer

if (total gt MAX)

Systemoutprintln (Error)errorCount++

Despite what is implied by the indentation theincrement will occur whether the condition istrue or not

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 25: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2585

copy 2007 Pearson Addison-Wesley All rights reserved 5-25

Block Statements

bull Several statements can be grouped together into ablock statement delimited by braces

bull A block statement can be used wherever a

statement is called for in the Java syntax rulesif (total gt MAX)

Systemoutprintln (Error)errorCount++

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 26: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2685

copy 2007 Pearson Addison-Wesley All rights reserved 5-26

Block Statements

bull In an if-else statement the if portion or theelse portion or both could be block statements

if (total gt MAX)

Systemoutprintln (Error)errorCount++

else

Systemoutprintln (Total + total)current = total2

bull See Guessingjava (page 223)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 27: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2785

copy 2007 Pearson Addison-Wesley All rights reserved 5-27

The Conditional Operator

bull Java has a conditional operator that uses aboolean condition to determine which of twoexpressions is evaluated

bull

Its syntax iscondition expression1 expression2

bull If the condition is true expression1 is

evaluated if it is false expression2 is evaluatedbull The value of the entire conditional operator is the

value of the selected expression

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 28: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2885

copy 2007 Pearson Addison-Wesley All rights reserved 5-28

The Conditional Operator

bull The conditional operator is similar to an if-else statementexcept that it is an expression that returns a value

bull For example

larger = ((num1 gt num2) num1 num2)

bull If num1 is greater than num2 then num1 is assigned tolarger otherwise num2 is assigned to larger

if (num1 gt num2)

larger = num1

else

larger = num2

bull The conditional operator is ternary because it requires threeoperands

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 29: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 2985

copy 2007 Pearson Addison-Wesley All rights reserved 5-29

The Conditional Operatorbull Another example

Systemoutprintln (Your change is + count +((count == 1) Dime Dimes))

bull If count equals 1 then Dime is printed

bull If count is anything other than 1 then Dimes isprinted

bull Note that the conditional expression cannot beused as a statement eg we cannot have astatement like

(num1 gt num2) larger = num1 larger = num2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 30: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3085

copy 2007 Pearson Addison-Wesley All rights reserved 5-30

Nested if Statements

bull The statement executed as a result of an if statement or else clause could be another if statement

bull

These are called nested if statements bull See MinOfThreejava (page 227)

bull An else clause is matched to the last unmatched

if above it (no matter what the indentationimplies)

bull Braces can be used to specify the if statement towhich an else clause belongs

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 31: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3185

copy 2007 Pearson Addison-Wesley All rights reserved 5-31

The switch Statement

bull The switch statement provides another way todecide which statement to execute next

bull The switch statement evaluates an expression

then attempts to match the result to one of severalpossible cases

bull Each case contains a value and a list ofstatements

bull The flow of control transfers to statementassociated with the first case value that matches

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 32: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3285

copy 2007 Pearson Addison-Wesley All rights reserved 5-32

The switch Statement

bull The general syntax of a switch statement isswitch ( expression )

case value1

statement-list1 case value2 statement-list2

case value3 statement-list3

case

switchand

case

arereservedwords

If expression matches value2 control jumpsto here

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 33: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3385

copy 2007 Pearson Addison-Wesley All rights reserved 5-33

The switch Statement

bull Often a break statement is used as the laststatement in each cases statement list

bull A break statement causes control to transfer to

the end of the switch statementbull If a break statement is not used the flow of

control will continue into the next case

bull

Sometimes this may be appropriate but often wewant to execute only the statements associatedwith one case

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 34: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3485

copy 2007 Pearson Addison-Wesley All rights reserved 5-34

The switch Statement

switch (option)

case AaCount++

breakcase B

bCount++ break

case C

cCount++ breakdefault

otherCount++

bull An example of a switch statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 35: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3585

copy 2007 Pearson Addison-Wesley All rights reserved 5-35

The switch Statement

bull A switch statement can have an optional default case

bull The default case has no associated value and

simply uses the reserved word default bull If the default case is present control will transfer

to it if no other case value matches

bull

If there is no default case and no other valuematches control falls through to the statementafter the switch

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 36: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3685

copy 2007 Pearson Addison-Wesley All rights reserved 5-36

The switch Statement

bull

The expression of a switch statement must resultin an integral type meaning an integer ( byte short int long ) or a char

bull It cannot be a boolean value or a floating pointvalue ( float or double )

bull The implicit boolean condition in a switch statement is equality

bull You cannot perform relational checks with aswitch statement

bull See GradeReportjava (page 233)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 37: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3785

copy 2007 Pearson Addison-Wesley All rights reserved 5-37

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 38: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3885

copy 2007 Pearson Addison-Wesley All rights reserved 5-38

Comparing Data

bull When comparing data using boolean expressionsits important to understand the nuances of certaindata types

bull

Lets examine some key situationsComparing floating point values for equalityComparing charactersComparing strings (alphabetical order)

Comparing object vs comparing object references

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 39: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 3985

copy 2007 Pearson Addison-Wesley All rights reserved 5-39

Comparing Float Values

bull You should rarely use the equality operator ( == )when comparing two floating point values ( float or double )

bull

Two floating point values are equal only if theirunderlying binary representations match exactly

bull Computations often result in slight differences thatmay be irrelevant

bull In many situations you might consider twofloating point numbers to be close enough evenif they arent exactly equal

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 40: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4085

copy 2007 Pearson Addison-Wesley All rights reserved 5-40

Comparing Float Values

bull To determine the equality of two floats you maywant to use the following technique

if (Mathabs(f1 - f2) lt TOLERANCE)Systemoutprintln (Essentially equal)

bull If the difference between the two floating pointvalues is less than the tolerance they areconsidered to be equal

bull The tolerance could be set to any appropriatelevel such as 0000001

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 41: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4185

copy 2007 Pearson Addison-Wesley All rights reserved 5-41

Comparing Characters

bull As weve discussed Java character data is basedon the Unicode character set

bull Unicode establishes a particular numeric value foreach character and therefore an ordering

bull We can use relational operators on character databased on this ordering

bull For example the character + is less than the

character J because it comes before it in theUnicode character set

bull Appendix C provides an overview of Unicode

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 42: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4285

copy 2007 Pearson Addison-Wesley All rights reserved 5-42

Comparing Characters

bull In Unicode the digit characters (0-9) arecontiguous and in order

bull Likewise the uppercase letters (A-Z) andlowercase letters (a-z) are contiguous and in order

Characters Unicode Values

0 ndash 9 48 through 57

A ndash Z 65 through 90a ndash z 97 through 122

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 43: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4385

copy 2007 Pearson Addison-Wesley All rights reserved 5-43

Comparing Strings

bull Remember that in Java a character string is anobject

bull The equals method can be called with strings todetermine if two strings contain exactly the samecharacters in the same order

bull The equals method returns a boolean result

if (name1equals(name2))Systemoutprintln (Same name)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 44: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4485

copy 2007 Pearson Addison-Wesley All rights reserved 5-44

Comparing Strings

bull We cannot use the relational operators to comparestrings

bull The String class contains a method calledcompareTo to determine if one string comesbefore another

bull A call to name1compareTo(name2)

returns zero if name1 and name2 are equal (contain thesame characters)

returns a negative value if name1 is less than name2

returns a positive value if name1 is greater than name2

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 45: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4585

copy 2007 Pearson Addison-Wesley All rights reserved 5-45

Comparing Strings

if (name1compareTo(name2) lt 0)Systemoutprintln (name1 + comes first)

elseif (name1compareTo(name2) == 0)

Systemoutprintln (Same name)else

Systemoutprintln (name2 + comes first)

bull Because comparing characters and strings isbased on a character set it is called alexicographic ordering

if (name1 lt name2) will not compile same as saying if (obj1 lt obj2)

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 46: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4685

copy 2007 Pearson Addison-Wesley All rights reserved 5-46

Lexicographic Ordering

bull

Lexicographic ordering is not strictly alphabeticalwhen uppercase and lowercase characters aremixed

bull For example the string Great comes before thestring fantastic because all of the uppercaseletters come before all of the lowercase letters inUnicode

bull

Also short strings come before longer stringswith the same prefix (lexicographically)

bull Therefore book comes before bookcase

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 47: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4785

copy 2007 Pearson Addison-Wesley All rights reserved 5-47

Comparing Objects

bull

The == operator can be applied to objects ndash itreturns true if the two references are aliases ofeach other

bull The equals method is defined for all objects but

unless we redefine it when we write a class it hasthe same semantics as the == operator

bull It has been redefined in the String class tocompare the characters in the two strings

bull When you write a class you can redefine theequals method to return true under whateverconditions are appropriate

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 48: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4885

copy 2007 Pearson Addison-Wesley All rights reserved 5-48

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 49: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 4985

copy 2007 Pearson Addison-Wesley All rights reserved 5-49

Repetition Statements

bull

Repetition statements allow us to execute astatement multiple timesbull Often they are referred to as loops bull Like conditional statements they are controlled by

boolean expressionsbull Java has three kinds of repetition statements

the while loop

the do loop the for loop

bull The programmer should choose the right kind ofloop for the situation

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 50: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5085

copy 2007 Pearson Addison-Wesley All rights reserved 5-50

The while Statement

bull A while statement has the following syntax while ( condition )

statement

bull If the condition is true the statement isexecuted

bull Then the condition is evaluated again and if it isstill true the statement is executed again

bull The statement is executed repeatedly until thecondition becomes false

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 51: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5185

copy 2007 Pearson Addison-Wesley All rights reserved 5-51

Logic of a while Loop

statement

true false

condition

evaluated

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 52: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5285

copy 2007 Pearson Addison-Wesley All rights reserved 5-52

The while Statement

bull An example of a while statementint count = 1

while (count lt= 5)

Systemoutprintln (count)

count++

bull If the condition of a while loop is false initially thestatement is never executed

bull Therefore the body of a while loop will executezero or more times

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 53: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5385

copy 2007 Pearson Addison-Wesley All rights reserved 5-53

The while Statement

bull Lets look at some examples of loop processingbull A loop can be used to maintain a running sum

bull A sentinel value is a special input value that

represents the end of inputbull See Averagejava (page 237)

bull A loop can also be used for input validation

making a program more robust bull See WinPercentagejava (page 239)

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 54: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5485

copy 2007 Pearson Addison-Wesley All rights reserved 5-54

Infinite Loops

bull The body of a while loop eventually must makethe condition false

bull If not it is called an infinite loop which willexecute until the user interrupts the program

bull This is a common logical error

bull You should always double check the logic of a

program to ensure that your loops will terminatenormally

f

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 55: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5585

copy 2007 Pearson Addison-Wesley All rights reserved 5-55

Infinite Loops

bull An example of an infinite loopint count = 1

while (count lt= 25)

Systemoutprintln (count)count = count - 1

bull This loop will continue executing until interrupted(Control-C) or until an underflow error occurs

d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 56: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5685

copy 2007 Pearson Addison-Wesley All rights reserved 5-56

Nested Loops

bull Similar to nested if statements loops can benested as well

bull That is the body of a loop can contain anotherloop

bull For each iteration of the outer loop the inner loopiterates completely

bull

See PalindromeTesterjava (page 243)

N d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 57: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5785

copy 2007 Pearson Addison-Wesley All rights reserved 5-57

Nested Loops

bull How many times will the string Here be printedcount1 = 1

while (count1 lt= 10)

count2 = 1

while (count2 lt= 20)

Systemoutprintln (Here)count2++

count1++ 10 20 = 200

O li

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 58: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5885

copy 2007 Pearson Addison-Wesley All rights reserved 5-58

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 59: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 5985

copy 2007 Pearson Addison-Wesley All rights reserved 5-59

Iterators

bull An iterator is an object that allows you to processa collection of items one at a time

bull It lets you step through each item in turn andprocess it as needed

bull An iterator object has a hasNext method thatreturns true if there is at least one more item toprocess

bull The next method returns the next item

bull Iterator objects are defined using the Iterator interface which is discussed further in Chapter 6

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 60: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6085

copy 2007 Pearson Addison-Wesley All rights reserved 5-60

Iterators

bull Several classes in the Java standard class libraryare iterators

bull The Scanner class is an iterator

the hasNext method returns true if there is more data tobe scanned

the next method returns the next scanned token as astring

bull The Scanner class also has variations on thehasNext method for specific data types (such ashasNextInt )

I

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 61: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6185

copy 2007 Pearson Addison-Wesley All rights reserved 5-61

Iterators

bull The fact that a Scanner is an iterator isparticularly helpful when reading input from a file

bull Suppose we wanted to read and process a list ofURLs stored in a file

bull One scanner can be set up to read each line of theinput until the end of the file is encountered

bull Another scanner can be set up for each URL toprocess each part of the path

bull See URLDissectorjava (page 247)

O tli

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 62: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6285

copy 2007 Pearson Addison-Wesley All rights reserved 5-62

Outline

The if Statement and ConditionsOther Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 63: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6385

copy 2007 Pearson Addison-Wesley All rights reserved 5-63

The do Statement

bull A do statement has the following syntaxdo

statement

while ( condition )

bull The statement is executed once initially and thenthe condition is evaluated

bull The statement is executed repeatedly until thecondition becomes false

L i f d L

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 64: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6485

copy 2007 Pearson Addison-Wesley All rights reserved 5-64

Logic of a do Loop

true

condition

evaluated

statement

false

Th d St t t

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 65: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6585

copy 2007 Pearson Addison-Wesley All rights reserved 5-65

The do Statement

bull An example of a do loop

bull The body of a do loop executes at least once

bull See ReverseNumberjava (page 251)

int count = 0do

count++

Systemoutprintln (count) while (count lt 5)

C i g hil d d

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 66: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6685

copy 2007 Pearson Addison-Wesley All rights reserved 5-66

Comparing while and do

statement

true false

condition

evaluated

The while Loop

true conditionevaluated

statement

false

The do Loop

The for St tement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 67: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6785

copy 2007 Pearson Addison-Wesley All rights reserved 5-67

The for Statement

bull A for statement has the following syntax

for ( initialization condition increment )statement

The initialization is executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed atthe end of each iteration

Logic of a for loop

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 68: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6885

copy 2007 Pearson Addison-Wesley All rights reserved 5-68

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 69: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 6985

copy 2007 Pearson Addison-Wesley All rights reserved 5-69

The for Statement

bull A for loop is functionally equivalent to thefollowing while loop structure

initialization while ( condition )

statement increment

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 70: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7085

copy 2007 Pearson Addison-Wesley All rights reserved 5-70

The for Statement

bull An example of a for loopfor (int count=1 count lt= 5 count++)

Systemoutprintln (count)

bull

The initialization section can be used to declare avariable

bull Like a while loop the condition of a for loop istested prior to executing the loop body

bull Therefore the body of a for loop will execute zeroor more times

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 71: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7185

copy 2007 Pearson Addison-Wesley All rights reserved 5-71

The for Statement

bull The increment section can perform any calculation

bull

A for loop is well suited for executing statementsa specific number of times that can be calculatedor determined in advance

bull See Multiplesjava (page 255)

bull See Starsjava (page 257)

for (int num=100 num gt 0 num -= 5)Systemoutprintln (num)

The for Statement

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 72: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7285

copy 2007 Pearson Addison-Wesley All rights reserved 5-72

The for Statement

bull Each expression in the header of a for loop isoptional

bull If the initialization is left out no initialization isperformed

bull If the condition is left out it is always consideredto be true and therefore creates an infinite loop

bull If the increment is left out no increment operationis performed

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 73: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7385

copy 2007 Pearson Addison-Wesley All rights reserved 5-73

Iterators and for Loops

bull Recall that an iterator is an object that allows youto process each item in a collection

bull A variant of the for loop simplifies the repetitiveprocessing the items

bull For example if BookList is an iterator thatmanages Book objects the following loop will printeach book

for (Book myBook BookList)Systemoutprintln (myBook)

Iterators and for Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 74: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7485

copy 2007 Pearson Addison-Wesley All rights reserved 5-74

Iterators and for Loops

bull This style of for loop can be read for each Book in BookList hellip

bull Therefore the iterator version of the for loop issometimes referred to as the foreach loop

bull It eliminates the need to call the hasNext andnext methods explicitly

bull It also will be helpful when processing arrayswhich are discussed in Chapter 7

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 75: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7585

copy 2007 Pearson Addison-Wesley All rights reserved 5-75

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Drawing Techniques

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 76: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7685

copy 2007 Pearson Addison-Wesley All rights reserved 5-76

Drawing Techniques

bull Conditionals and loops enhance our ability togenerate interesting graphics

bull See Bullseyejava (page 259)bull

See BullseyePaneljava (page 290)bull See Boxesjava (page 262)bull See BoxesPaneljava (page 263)

Determining Event Sources

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 77: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7785

copy 2007 Pearson Addison-Wesley All rights reserved 5-77

Determining Event Sources

bull Recall that interactive GUIs require establishing arelationship between components and thelisteners that respond to component events

bull One listener object can be used to listen to twodifferent components

bull The source of the event can be determined byusing the getSource method of the event passed

to the listenerbull See LeftRightjava (page 265)bull See LeftRightPaneljava (page 266)

Outline

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 78: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7885

copy 2007 Pearson Addison-Wesley All rights reserved 5-78

Outline

The if Statement and Conditions

Other Conditional Statements

Comparing Data

The while Statement

Iterators

Other Repetition Statements

Decisions and Graphics

More Components

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 79: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 7985

copy 2007 Pearson Addison-Wesley All rights reserved 5-79

Dialog Boxes

bull A dialog box is a window that appears on top ofany currently active window

bull It may be used to

convey informationconfirm an actionallow the user to enter datapick a colorchoose a file

bull A dialog box usually has a specific solitarypurpose and the user interaction with it is brief

Dialog Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 80: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8085

copy 2007 Pearson Addison-Wesley All rights reserved 5-80

Dialog Boxes

bull The JOptionPane class provides methods thatsimplify the creation of some types of dialogboxes

bull See EvenOddjava (page 268)

bull We examine dialog boxes for choosing colors andfiles in Chapter 9

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 81: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8185

copy 2007 Pearson Addison-Wesley All rights reserved 5-81

Check Boxes

bull

A check box is a button that can be toggled on oroff

bull It is represented by the JCheckBox class

bull

Unlike a push button which generates an actionevent a check box generates an item event whenever it changes state (is checked on or off)

bull The ItemListener interface is used to define item

event listenersbull The check box calls the itemStateChanged

method of the listener when it is toggled

Check Boxes

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 82: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8285

copy 2007 Pearson Addison-Wesley All rights reserved 5-82

Check Boxes

bull Lets examine a program that uses check boxes todetermine the style of a labels text string

bull It uses the Font class which represents acharacter fonts

family name (such as Times or Courier)style (bold italic or both)font size

bull See StyleOptionsjava (page 271)bull See StyleOptionsPaneljava (page 272)

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 83: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8385

copy 2007 Pearson Addison-Wesley All rights reserved 5-83

Radio Buttons

bull A group of radio buttons represents a set ofmutually exclusive options ndash only one can beselected at any given time

bull When a radio button from a group is selected thebutton that is currently on in the group isautomatically toggled off

bull To define the group of radio buttons that will work

together each radio button is added to aButtonGroup object

bull A radio button generates an action event

Radio Buttons

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 84: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8485

copy 2007 Pearson Addison-Wesley All rights reserved 5-84

Radio Buttons

bull Lets look at a program that uses radio buttons todetermine which line of text to display

bull See QuoteOptionsjava (page 275) bull See QuoteOptionsPaneljava (page 276)

bull Compare and contrast check boxes and radiobuttons

Check boxes work independently to provide a booleanoption

Radio buttons work as a group to provide a set ofmutually exclusive options

Summary

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components

Page 85: Lewis Chap 5 - Conditionals and Loops

822019 Lewis Chap 5 - Conditionals and Loops

httpslidepdfcomreaderfulllewis-chap-5-conditionals-and-loops 8585

Summary

bull Chapter 5 focused onboolean expressionsconditional statementscomparing data

repetition statementsiteratorsmore drawing techniquesmore GUI components