• No results found

Chapter 3: Program Statements Chapter 3: Program Statements

N/A
N/A
Protected

Academic year: 2021

Share "Chapter 3: Program Statements Chapter 3: Program Statements"

Copied!
58
0
0

Loading.... (view fulltext now)

Full text

(1)

Chapter 3: Program Statements Chapter 3: Program Statements

Presentation slides for Presentation slides for

Java Software Solutions Java Software Solutions

Foundations of Program Design Foundations of Program Design

Second Edition Second Edition

by John Lewis and William Loftus by John Lewis and William Loftus

Java Software Solutions is published by Addison-Wesley Java Software Solutions is published by Addison-Wesley

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.

Presentation slides are copyright 2000 by John Lewis and William Loftus. All rights reserved.

Instructors using the textbook may use and modify these slides for pedagogical purposes.

Instructors using the textbook may use and modify these slides for pedagogical purposes.

(2)

2

Program Statements Program Statements

We will now examine some other program statementsWe will now examine some other program statements

Chapter 3 focuses on:Chapter 3 focuses on:

the flow of control through a methodthe flow of control through a method

decision-making statementsdecision-making statements

operators for making complex decisionsoperators for making complex decisions

repetition statementsrepetition statements

software development stagessoftware development stages

more drawing techniquesmore drawing techniques

(3)

Flow of Control Flow of Control

Unless indicated otherwise, the order of statement Unless indicated otherwise, the order of statement

execution through a method is linear: one after the other in execution through a method is linear: one after the other in

the order they are written the order they are written

Some programming statements modify that order, allowing Some programming statements modify that order, allowing us to:

us to:

decide whether or not to execute a particular statement, ordecide whether or not to execute a particular statement, or

perform a statement over and over repetitivelyperform a statement over and over repetitively

The order of statement execution is called the The order of statement execution is called the flow of flow of control

control

(4)

Conditional Statements Conditional Statements

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

be executed next

Therefore they are sometimes called Therefore they are sometimes called selection statementsselection statements

Conditional statements give us the power to make basic Conditional statements give us the power to make basic decisions

decisions

Java's conditional statements are the Java's conditional statements are the if statementif statement, the , the if-else if-else statement

statement, and the switch statement, and the switch statement

(5)

The if Statement The if Statement

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

if ( condition ) statement;

if is a Javaif is a Java reserved word reserved word

The condition must be a

The condition must be a boolean expressionboolean expression.. It must evaluate to either true or false.

It must evaluate to either true or false.

If the condition is true, the statement is executed.

If the condition is true, the statement is executed.

If it is false, the statement is skipped.

If it is false, the statement is skipped.

(6)

The if Statement The if Statement

An example of an if statement:An example of an if statement:

if (sum > MAX)

delta = sum - MAX;

System.out.println ("The sum is " + sum);

First, the condition is evaluated. The value of

First, the condition is evaluated. The value of sumsum is either greater than the value of

is either greater than the value of MAXMAX, or it is not., or it is not.

If the condition is true, the assignment statement is executed.

If the condition is true, the assignment statement is executed.

If it is not, the assignment statement is skipped.

If it is not, the assignment statement is skipped.

Either way, the call to println is executed next.

Either way, the call to println is executed next.

See See Age.java Age.java (page 112)(page 112)

(7)

Logic of an if statement Logic of an if statement

condition evaluated

false false statement

truetrue

(8)

8

Boolean Expressions Boolean Expressions

A condition often uses one of Java's A condition often uses one of Java's equality operators equality operators or or relational operators

relational operators, which all return boolean results:, which all return boolean results:

==== equal toequal to

!=!= not equal tonot equal to

<< less thanless than

>> greater thangreater than

<=

<= less than or equal toless than or equal to

>=

>= greater than or equal togreater than or equal to

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

the assignment operator (=)=)

(9)

The if-else Statement The if-else Statement

An An else clauseelse clause can be added to an if statement to make it an can be added to an if statement to make it an if-else statement

if-else statement::

if ( condition ) statement1;

else

statement2;

See See Wages.java Wages.java (page 116)(page 116)

If the condition is true, statement1 is executed; if the If the condition is true, statement1 is executed; if the condition is false, statement2 is executed

condition is false, statement2 is executed

One or the other will be executed, but not bothOne or the other will be executed, but not both

(10)

Logic of an if-else statement Logic of an if-else statement

condition evaluated

statement1

truetrue falsefalse statement2

(11)

Block Statements Block Statements

Several statements can be grouped together into a Several statements can be grouped together into a block block statement

statement

A block is delimited by braces ( { … } )A block is delimited by braces ( { … } )

A block statement can be used wherever a statement is A block statement can be used wherever a statement is called for in the Java syntax

called for in the Java syntax

For example, in an if-else statement, the if portion, or the For example, in an if-else statement, the if portion, or the else portion, or both, could be block statements

else portion, or both, could be block statements

See See Guessing.java Guessing.java (page 117)(page 117)

(12)

12

Nested if Statements Nested if Statements

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

clause could be another if statement

These are called These are called nested if statementsnested if statements

See MinOfThree.java (page 118)See MinOfThree.java (page 118)

An else clause is matched to the last unmatched if (no An else clause is matched to the last unmatched if (no matter what the indentation implies)

matter what the indentation implies)

(13)

Comparing Characters Comparing Characters

We can use the relational operators on character dataWe can use the relational operators on character data

The results are based on the Unicode character setThe results are based on the Unicode character set

The following condition is true because the character '+' The following condition is true because the character '+' comes before the character 'J' in Unicode:

comes before the character 'J' in Unicode:

if ('+' < 'J')

System.out.println ("+ is less than J");

The uppercase alphabet (A-Z) and the lowercase alphabet The uppercase alphabet (A-Z) and the lowercase alphabet (a-z) both appear in alphabetical order in Unicode

(a-z) both appear in alphabetical order in Unicode

(14)

Comparing Strings Comparing Strings

Remember that a character string in Java is an objectRemember that a character string in Java is an object

We cannot use the relational operators to compare stringsWe cannot use the relational operators to compare strings

The The equalsequals method can be called on a string to determine method can be called on a string to determine if two strings contain exactly the same characters in the

if two strings contain exactly the same characters in the same order

same order

The String class also contains a method called The String class also contains a method called compareTocompareTo to determine if one string comes before another

to determine if one string comes before another

alphabetically (as determined by the Unicode character set) alphabetically (as determined by the Unicode character set)

(15)

Comparing Floating Point Values Comparing Floating Point Values

We also have to be careful when comparing two floating We also have to be careful when comparing two floating point values (

point values (floatfloat or or doubledouble) for equality) for equality

You should rarely use the equality operator (You should rarely use the equality operator (====) when ) when comparing two floats

comparing two floats

In many situations, you might consider two floating point In many situations, you might consider two floating point numbers to be "close enough" even if they aren't exactly numbers to be "close enough" even if they aren't exactly

equal equal

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

want to use the following technique:

if (Math.abs (f1 - f2) < 0.00001)

System.out.println ("Essentially equal.");

(16)

16

The switch Statement The switch Statement

The The switch statementswitch statement provides another means to decide provides another means to decide which statement to execute next

which statement to execute next

The switch statement evaluates an expression, then The switch statement evaluates an expression, then attempts to match the result to one of several possible

attempts to match the result to one of several possible casescases

Each case contains a value and a list of statementsEach case contains a value and a list of statements

The flow of control transfers to statement list associated The flow of control transfers to statement list associated with the first value that matches

with the first value that matches

(17)

The switch Statement The switch Statement

The general syntax of a switch statement is:The general syntax of a switch statement is:

switch ( expression ) {

case value1 :

statement-list1 case value2 :

statement-list2 case value3 :

statement-list3 case ...

} switch

switch andand casecase

areare reserved reserved

words words

If If expressionexpression matches

matches value2,value2, control jumps control jumps

to here to here

(18)

The switch Statement The switch Statement

Often a Often a break statementbreak statement is used as the last statement in each is used as the last statement in each case's statement list

case's statement list

A break statement causes control to transfer to the end of A break statement causes control to transfer to the end of the switch statement

the switch statement

If a break statement is not used, the flow of control will If a break statement is not used, the flow of control will continue into the next case

continue into the next case

Sometimes this can be helpful, but usually we only want to Sometimes this can be helpful, but usually we only want to execute the statements associated with one case

execute the statements associated with one case

(19)

The switch Statement The switch Statement

A switch statement can have an optional A switch statement can have an optional default casedefault case

The default case has no associated value and simply uses the The default case has no associated value and simply uses the reserved word

reserved word defaultdefault

If the default case is present, control will transfer to it if no If the default case is present, control will transfer to it if no other case value matches

other case value matches

Though the default case can be positioned anywhere in the Though the default case can be positioned anywhere in the switch, it is usually placed at the end

switch, it is usually placed at the end

If there is no default case, and no other value matches, If there is no default case, and no other value matches, control falls through to the statement after the switch control falls through to the statement after the switch

(20)

The switch Statement The switch Statement

The expression of a switch statement must result in an The expression of a switch statement must result in an integral data type

integral data type, like an integer or character; it cannot be , like an integer or character; it cannot be a floating point value

a floating point value

Note that the implicit boolean condition in a switch Note that the implicit boolean condition in a switch

statement is equality - it tries to match the expression with statement is equality - it tries to match the expression with

a value a value

You cannot perform relational checks with a switch You cannot perform relational checks with a switch statement

statement

See GradeReport.java (page 121)See GradeReport.java (page 121)

(21)

Logical Operators Logical Operators

Boolean expressions can also use the following Boolean expressions can also use the following logical logical operators

operators::

!!Logical NOTLogical NOT

&&

&& Logical ANDLogical AND

|||| Logical ORLogical OR

They all take boolean operands and produce boolean resultsThey all take boolean operands and produce boolean results

Logical NOT is a unary operator (it has one operand), but Logical NOT is a unary operator (it has one operand), but logical AND and logical OR are binary operators (they each logical AND and logical OR are binary operators (they each have two operands)

have two operands)

(22)

22

Logical NOT Logical NOT

The The logical NOTlogical NOT operation is also called operation is also called logical negationlogical negation or or logical complement

logical complement

If some boolean condition If some boolean condition aa is true, then is true, then !a!a is false; if is false; if aa is is false, then

false, then !a!a is true is true

Logical expressions can be shown using Logical expressions can be shown using truth tablestruth tables

a true false

!a false

true

(23)

Logical AND and Logical OR Logical AND and Logical OR

The The logical andlogical and expression expression

a && b is true if both

is true if both aa and and bb are true, and false otherwise are true, and false otherwise

The The logical orlogical or expression expression

a || b

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

(24)

Truth Tables Truth Tables

A truth table shows the possible true/false combinations of A truth table shows the possible true/false combinations of the terms

the terms

Since Since &&&& and and |||| each have two operands, there are four each have two operands, there are four possible combinations of true and false

possible combinations of true and false

a true true false false

b true false

true false

a && b true false false false

a || b true true true false

(25)

Logical Operators Logical Operators

Conditions in selection statements and loops can use logical Conditions in selection statements and loops can use logical operators to form complex expressions

operators to form complex expressions

if (total < MAX && !found)

System.out.println ("Processing…");

Logical operators have precedence relationships between Logical operators have precedence relationships between themselves and other operators

themselves and other operators

(26)

26

Truth Tables Truth Tables

Specific expressions can be evaluated using truth tablesSpecific expressions can be evaluated using truth tables

total < MAX false

false true true

found false

true false

true

!found true false

true false

total < MAX && !found

false false true false

(27)

More Operators More Operators

To round out our knowledge of Java operators, let's To round out our knowledge of Java operators, let's examine a few more

examine a few more

In particular, we will examine the:In particular, we will examine the:

increment and decrement operatorsincrement and decrement operators

assignment operatorsassignment operators

conditional operatorconditional operator

(28)

28

Increment and Decrement Increment and Decrement

Operators Operators

The increment and decrement operators are arithmetic and The increment and decrement operators are arithmetic and operate on one operand

operate on one operand

The The increment operatorincrement operator ( (++++) adds one to its operand) adds one to its operand

The The decrement operatordecrement operator ( (----) subtracts one from its operand) subtracts one from its operand

The statementThe statement

count++;

is essentially equivalent to is essentially equivalent to

count = count + 1;

(29)

Increment and Decrement Increment and Decrement

Operators Operators

The increment and decrement operators can be applied in The increment and decrement operators can be applied in prefix form

prefix form (before the variable) or (before the variable) or postfix formpostfix form (after the (after the variable)

variable)

When used alone in a statement, the prefix and postfix When used alone in a statement, the prefix and postfix forms are basically equivalent. That is,

forms are basically equivalent. That is,

count++;

is equivalent to is equivalent to

++count;

(30)

30

Increment and Decrement Increment and Decrement

Operators Operators

When used in a larger expression, the prefix and postfix When used in a larger expression, the prefix and postfix forms have a different effect

forms have a different effect

In both cases the variable is incremented (decremented)In both cases the variable is incremented (decremented)

But the value used in the larger expression depends on the But the value used in the larger expression depends on the form:

form:

Expression count++

++count count-- --count

Operation add 1 add 1 subtract 1 subtract 1

Value of Expression old value

new value old value new value

(31)

Increment and Decrement Increment and Decrement

Operators Operators

If If countcount currently contains 45, then currently contains 45, then

total = count++;

assigns 45 to

assigns 45 to total and 46 to total and 46 to countcount

If If countcount currently contains 45, then currently contains 45, then

total = ++count;

assigns the value 46 to both

assigns the value 46 to both total and total and countcount

(32)

32

Assignment Operators Assignment Operators

Often we perform an operation on a variable, then store the Often we perform an operation on a variable, then store the result back into that variable

result back into that variable

Java provides Java provides assignment operatorsassignment operators to simplify that process to simplify that process

For example, the statementFor example, the statement

num += count;

is equivalent to is equivalent to

num = num + count;

(33)

Assignment Operators Assignment Operators

There are many assignment operators, including the There are many assignment operators, including the following:

following:

Operator +=

-=

*=

/=

%=

Example x += y x -= y x *= y x /= y x %= y

Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y

(34)

34

Assignment Operators Assignment Operators

The right hand side of an assignment operator can be a The right hand side of an assignment operator can be a complete expression

complete expression

The entire right-hand expression is evaluated first, then the The entire right-hand expression is evaluated first, then the result is combined with the original variable

result is combined with the original variable

ThereforeTherefore

result /= (total-MIN) % num;

is equivalent to is equivalent to

result = result / ((total-MIN) % num);

(35)

The Conditional Operator The Conditional Operator

Java has a Java has a conditional operatorconditional operator that evaluates a boolean that evaluates a boolean

condition that determines which of two other expressions is condition that determines which of two other expressions is evaluated

evaluated

The result of the chosen expression is the result of the entire The result of the chosen expression is the result of the entire conditional operator

conditional operator

Its syntax is:Its syntax is:

condition ? expression1 : expression2

If the If the conditioncondition is true, is true, expression1expression1 is evaluated; if it is false, is evaluated; if it is false, expression2

expression2 is evaluated is evaluated

(36)

36

The Conditional Operator The Conditional Operator

The conditional operator is similar to an if-else statement, The conditional operator is similar to an if-else statement, except that it is an expression that returns a value

except that it is an expression that returns a value

For example:For example:

larger = (num1 > num2) ? num1 : num2;

If If num1num1 is greater that is greater that num2num2, then , then num1num1 is assigned to is assigned to larger

larger; otherwise, ; otherwise, num2num2 is assigned to is assigned to largerlarger

The conditional operator is The conditional operator is ternaryternary, meaning that it , meaning that it requires three operands

requires three operands

(37)

The Conditional Operator The Conditional Operator

Another example:Another example:

System.out.println ("Your change is " + count + (count == 1) ? "Dime" : "Dimes");

If If countcount equals 1, then equals 1, then "Dime" is printed"Dime" is printed

If If countcount is anything other than 1, then is anything other than 1, then "Dimes""Dimes" is is printed

printed

(38)

Repetition Statements Repetition Statements

Repetition statementsRepetition statements allow us to execute a statement multiple allow us to execute a statement multiple times repetitively

times repetitively

They are often simply referred to as They are often simply referred to as loopsloops

Like conditional statements, they are controlled by boolean Like conditional statements, they are controlled by boolean expressions

expressions

Java has three kinds of repetition statements: the Java has three kinds of repetition statements: the while loopwhile loop, , the the do loopdo loop, and the , and the for loopfor loop

The programmer must choose the right kind of loop for the The programmer must choose the right kind of loop for the situation

situation

(39)

The while Statement The while Statement

The The while statementwhile statement has the following syntax: has the following syntax:

while ( condition ) statement;

while while is a is a reserved word reserved word

If the condition is true, the statement is executed.

If the condition is true, the statement is executed.

Then the condition is evaluated again.

Then the condition is evaluated again.

The statement is executed repetitively until The statement is executed repetitively until

the condition becomes false.

the condition becomes false.

(40)

Logic of a while loop Logic of a while loop

statement truetrue condition evaluated

false false

(41)

The while Statement The while Statement

Note that if the condition of a whileNote that if the condition of a while statement is false statement is false initially, the statement is never executed

initially, the statement is never executed

Therefore, the body of a while loop will execute zero or Therefore, the body of a while loop will execute zero or more times

more times

See Counter.java (page 133)See Counter.java (page 133)

See Average.java (page 134)See Average.java (page 134)

See WinPercentage.java (page 136)See WinPercentage.java (page 136)

(42)

42

Infinite Loops Infinite Loops

The body of a whileThe body of a while loop must eventually make the loop must eventually make the condition false

condition false

If not, it is an If not, it is an infinite loopinfinite loop, which will execute until the user , which will execute until the user interrupts the program

interrupts the program

See Forever.java (page 138) See Forever.java (page 138)

This is a common type of logical errorThis is a common type of logical error

You should always double check to ensure that your loops You should always double check to ensure that your loops will terminate normally

will terminate normally

(43)

Nested Loops Nested Loops

Similar to nested if statements, loops can be nested as wellSimilar to nested if statements, loops can be nested as well

That is, the body of a loop could contain another loopThat is, the body of a loop could contain another loop

Each time through the outer loop, the inner loop will go Each time through the outer loop, the inner loop will go through its entire set of iterations

through its entire set of iterations

See PalindromeTester.java (page 137)See PalindromeTester.java (page 137)

(44)

The do Statement The do Statement

The The do statementdo statement has the following syntax: has the following syntax:

do {

statement;

}

while ( condition ) Uses both

Uses both the the dodo and and

while while reserved reserved

words words

The statement is executed once initially, then the condition is evaluated The statement is executed once initially, then the condition is evaluated

The statement is repetitively executed until the condition becomes false The statement is repetitively executed until the condition becomes false

(45)

Logic of a do loop Logic of a do loop

truetrue

condition evaluated statement

false false

(46)

The do Statement The do Statement

A do loop is similar to a while loop, except that the A do loop is similar to a while loop, except that the

condition is evaluated after the body of the loop is executed condition is evaluated after the body of the loop is executed

Therefore the body of a do loop will execute at least one Therefore the body of a do loop will execute at least one timetime

See Counter2.java (page 143)See Counter2.java (page 143)

See ReverseNumber.java (page 144)See ReverseNumber.java (page 144)

(47)

Comparing the while and do Comparing the while and do

loops loops

statement truetrue condition evaluated

false false

while loop while loop

truetrue

condition evaluated statement

false false

do loop do loop

(48)

The for Statement The for Statement

The The for statementfor statement has the following syntax: has the following syntax:

for ( initialization ; condition ; increment ) statement;

Reserved Reserved

wordword

The initializationThe initialization portion portion is executed once

is executed once before the loop begins before the loop begins

The statement is The statement is executed until the executed until the condition

condition becomes false becomes false

The incrementThe increment portion is executed at the end of each iteration portion is executed at the end of each iteration

(49)

The for Statement The for Statement

A for loop is equivalent to the following while loop A for loop is equivalent to the following while loop structure:

structure:

initialization;

while ( condition ) {

statement;

increment;

}

(50)

Logic of a for loop Logic of a for loop

statement truetrue condition evaluated

false false

increment initialization

(51)

The for Statement The for Statement

Like a while loop, the condition of a for statement is tested Like a while loop, the condition of a for statement is tested prior to executing the loop body

prior to executing the loop body

Therefore, the body of a for loop will execute zero or more Therefore, the body of a for loop will execute zero or more times

times

It is well suited for executing a specific number of times It is well suited for executing a specific number of times that can be determined in advance

that can be determined in advance

See Counter3.java (page 146)See Counter3.java (page 146)

See Multiples.java (page 147)See Multiples.java (page 147)

See Stars.java (page 150)See Stars.java (page 150)

(52)

The for Statement The for Statement

Each expression in the header of a for loop is optionalEach expression in the header of a for loop is optional

If the initialization is left out, no initialization is performedIf the initialization is left out, no initialization is performed

If the condition is left out, it is always considered to be true, and If the condition is left out, it is always considered to be true, and therefore creates an infinite loop

therefore creates an infinite loop

If the increment is left out, no increment operation is performedIf the increment is left out, no increment operation is performed

Both semi-colons are always required in the for loop headerBoth semi-colons are always required in the for loop header

(53)

Program Development Program Development

The creation of software involves four basic activities:The creation of software involves four basic activities:

establishing the requirementsestablishing the requirements

creating a designcreating a design

implementing the codeimplementing the code

testing the implementationtesting the implementation

The development process is much more involved than this, The development process is much more involved than this, but these basic steps are a good starting point

but these basic steps are a good starting point

(54)

54

Requirements Requirements

RequirementsRequirements specify the tasks a program must accomplish specify the tasks a program must accomplish (what to do, not how to do it)

(what to do, not how to do it)

They often include a description of the user interfaceThey often include a description of the user interface

An initial set of requirements are often provided, but An initial set of requirements are often provided, but usually must be critiqued, modified, and expanded usually must be critiqued, modified, and expanded

It is often difficult to establish detailed, unambiguous, It is often difficult to establish detailed, unambiguous, complete requirements

complete requirements

Careful attention to the requirements can save significant Careful attention to the requirements can save significant time and money in the overall project

time and money in the overall project

(55)

Design Design

An An algorithmalgorithm is a step-by-step process for solving a problem is a step-by-step process for solving a problem

A program follows one or more algorithms to accomplish A program follows one or more algorithms to accomplish its goal

its goal

The The designdesign of a program specifies the algorithms and data of a program specifies the algorithms and data needed

needed

In object-oriented development, the design establishes the In object-oriented development, the design establishes the classes, objects, and methods that are required

classes, objects, and methods that are required

The details of a method may be expressed in The details of a method may be expressed in pseudocodepseudocode, , which is code-like, but does not necessarily follow any which is code-like, but does not necessarily follow any

specific syntax specific syntax

(56)

56

Implementation Implementation

ImplementationImplementation is the process of translating a design into is the process of translating a design into source code

source code

Most novice programmers think that writing code is the Most novice programmers think that writing code is the

heart of software development, but it actually should be the heart of software development, but it actually should be the

least creative step least creative step

Almost all important decisions are made during Almost all important decisions are made during requirements analysis and design

requirements analysis and design

Implementation should focus on coding details, including Implementation should focus on coding details, including style guidelines and documentation

style guidelines and documentation

See ExamGrades.java (page 155)See ExamGrades.java (page 155)

(57)

Testing Testing

A program should be executed multiple times with various A program should be executed multiple times with various input in an attempt to find errors

input in an attempt to find errors

DebuggingDebugging is the process of discovering the cause of a is the process of discovering the cause of a problem and fixing it

problem and fixing it

Programmers often erroneously think that there is "only Programmers often erroneously think that there is "only one more bug" to fix

one more bug" to fix

Tests should focus on design details as well as overall Tests should focus on design details as well as overall requirements

requirements

(58)

More Drawing Techniques More Drawing Techniques

Conditionals and loops can greatly enhance our ability to Conditionals and loops can greatly enhance our ability to control graphics

control graphics

See Bullseye.java (page 157)See Bullseye.java (page 157)

See Boxes.java (page 159)See Boxes.java (page 159)

See BarHeights.java (page 162) See BarHeights.java (page 162)

References

Related documents