flow of control (1) : logic clark savage turner, j.d., ph.d. [email protected] some...

30
Flow of Control Flow of Control (1) (1) : : Logic Logic Clark Savage Turner, J.D., Ph.D. Clark Savage Turner, J.D., Ph.D. [email protected] [email protected] 756-6133 756-6133 Some lecture slides have been adapted from those Some lecture slides have been adapted from those developed developed by by John Lewis and William Loftus to accompany John Lewis and William Loftus to accompany Java Software Solutions: Java Software Solutions: Foundations of Program Design, Second Edition Foundations of Program Design, Second Edition and and by Mark Hutchenreuther for CSC-101 at Cal Poly, SLO. by Mark Hutchenreuther for CSC-101 at Cal Poly, SLO.

Post on 20-Dec-2015

217 views

Category:

Documents


2 download

TRANSCRIPT

Flow of Control Flow of Control (1)(1) : Logic : Logic

Clark Savage Turner, J.D., Ph.D.Clark Savage Turner, J.D., Ph.D.

[email protected]@csc.calpoly.edu

756-6133756-6133

Some lecture slides have been adapted from those developedSome lecture slides have been adapted from those developed by by John Lewis and William Loftus to accompany John Lewis and William Loftus to accompany

Java Software Solutions: Java Software Solutions: Foundations of Program Design, Second EditionFoundations of Program Design, Second Edition

and and

by Mark Hutchenreuther for CSC-101 at Cal Poly, SLO. by Mark Hutchenreuther for CSC-101 at Cal Poly, SLO.

2

CSC-101

Formatting Output - reviewFormatting Output - review

The The DecimalFormatDecimalFormat class can be used to format a class can be used to format a floating point value in generic waysfloating point value in generic ways

For example, you can specify that the number be printed to For example, you can specify that the number be printed to three decimal placesthree decimal places

The constructor of the The constructor of the DecimalFormatDecimalFormat class takes a class takes a string that represents a pattern for the formatted numberstring that represents a pattern for the formatted number

See CircleStats.java, which uses 0.### where: See CircleStats.java, which uses 0.### where: 0 means show the leading 0 if the value is less than 1, and0 means show the leading 0 if the value is less than 1, and ### means round to three decimal places.### means round to three decimal places.

3

CSC-101

DecimalFormat versus NumberFormatDecimalFormat versus NumberFormat

DecimalFormat does use the DecimalFormat does use the newnew operator to instantiate it. operator to instantiate it. See CircleStats.java See CircleStats.java

NumberFormat does not use the NumberFormat does not use the newnew operator... operator... See Price.java See Price.java

4

CSC-101

Flow of ControlFlow 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 writtenthe 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 controlcontrol

5

CSC-101

Conditional StatementsConditional Statements

A A conditional statementconditional statement lets us choose which statement will lets us choose which statement will be executed nextbe 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 decisionsdecisions

Java's conditional statements are the Java's conditional statements are the if statementif statement, the , the if-else if-else statementstatement, and the , and the switch statementswitch statement

6

CSC-101

Logic of an if statementLogic of an if statement

conditionevaluated

falsefalse

statement

truetrue

7

CSC-101

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

conditionevaluated

statement1

truetrue falsefalse

statement2

8

CSC-101

The if StatementThe if Statement

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

if ( condition ) statement;

ifif is a Java is a Javareserved wordreserved 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.

9

CSC-101

The The ifif Statement 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 sumsumis 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.Age.javajava

10

CSC-101

The if StatementThe 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 sumsumis 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 Age.java See Age.java

11

CSC-101

Block StatementsBlock Statements

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

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

A block statement can be used wherever A block statement can be used wherever a statement is called for in the Java syntax a statement is 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 statementselse portion, or both, could be block statements

See See Guessing.Guessing.javajava

12

CSC-101

Another Another ifif Statement Statement

Another example of an if statement:Another example of an if statement:if (sum > MAX) { delta = sum - MAX; System.out.print ("Delta is " + delta + ".\t"); }System.out.println ("The sum is " + sum + ".");

First, the condition is evaluated. The value of First, the condition is evaluated. The value of sumsumis 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, them the assignment statement If the condition is true, them the assignment statement andand the first S.o.p are executed. the first S.o.p are 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.

13

CSC-101

Boolean ExpressionsBoolean Expressions

A condition often uses one of Java's A condition often uses one of Java's equality operators equality operators or or relational operatorsrelational 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 these:Note the difference between these: the equality operator (the equality operator (====) ) the assignment operator (the assignment operator (==))

14

CSC-101

Logical OperatorsLogical Operators

Boolean expressions can also use the following Boolean expressions can also use the following logical logical operatorsoperators::

!! Logical NOTLogical NOT

&&&& Logical ANDLogical AND

|||| Logical ORLogical OR

They all take boolean operands and produce boolean They all take boolean operands and produce boolean resultsresults

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 logical AND and logical OR are binary operators (they each have two operands)each have two operands)

15

CSC-101

Logical NOTLogical NOT

The The logical NOTlogical NOT operation is also called operation is also called logical negationlogical negation or or logical complementlogical 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

truefalse

!a

falsetrue

16

CSC-101

Logical AND and Logical ORLogical 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 otherwiseis true if a or b or both are true, and false otherwise

17

CSC-101

Truth TablesTruth Tables

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

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

a

truetruefalsefalse

b

truefalsetruefalse

a && b

truefalsefalsefalse

a || b

truetruetruefalse

18

CSC-101

The if-else StatementThe 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 statementif-else statement::

if ( condition ) statement1;else statement2;

See See Wages.Wages.javajava

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 executedcondition is false, statement2 is executed

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

19

CSC-101

Nested if StatementsNested 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 statementclause could be another if statement

These are called These are called nested if statementsnested if statements

See See MinOfThreeMinOfThree.java .java

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)

20

CSC-101

Comparing CharactersComparing 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

21

CSC-101

Comparing StringsComparing 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 ordersame 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)

22

CSC-101

Comparing Floating Point ValuesComparing 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 floatscomparing 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 equalequal

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

23

CSC-101

Increment and Decrement OperatorsIncrement and Decrement Operators

The increment and decrement operators are arithmetic and The increment and decrement operators are arithmetic and operate on one operandoperate 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 tois essentially equivalent to

count = count + 1;

24

CSC-101

Increment and Decrement OperatorsIncrement and Decrement Operators

The increment and decrement operators can be applied in The increment and decrement operators can be applied in prefix formprefix 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 tois equivalent to

++count;

25

CSC-101

Increment and Decrement OperatorsIncrement and Decrement 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 effectforms 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++++countcount----count

Operation

add 1add 1

subtract 1subtract 1

Value of Expression

old valuenew valueold valuenew value

26

CSC-101

Increment and Decrement OperatorsIncrement and Decrement Operators

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

total = count++;

assigns 45 to assigns 45 to totaltotal and 46 to 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 totaltotal and and countcount

27

CSC-101

Assignment OperatorsAssignment 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 variableresult 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 tois equivalent to num = num + count;

For CPE101, however, For CPE101, however, avoidavoid those those assignment operatorsassignment operators: : they tend to obscure what you are really doing, so...they tend to obscure what you are really doing, so... they are a major source of logical errors, andthey are a major source of logical errors, and they make your code harder for others to quickly understand.they make your code harder for others to quickly understand.

28

CSC-101

The Conditional OperatorThe 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 evaluatedevaluated

The result of the chosen expression is the result of the The result of the chosen expression is the result of the entire conditional operatorentire 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 is evaluated; if it is false, false, expression2expression2 is evaluated is evaluated

29

CSC-101

The Conditional OperatorThe 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 valueexcept 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 largerlarger; 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 operandsrequires three operands

30

CSC-101

The Conditional OperatorThe 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""Dime" is printed is printed If If countcount is anything other than 1, then is anything other than 1, then "Dimes""Dimes" is is

printedprinted