© 2005 lawrenceville press slide 1 chapter 5 relational operators relational operatormeaning...

27
© 2005 Lawrenceville Press Slide 1 Chapter 5 Chapter 5 Relational Operators Relational Operators Relational Operator Meaning < less than <= less than or equal > greater than >= greater than or equal Equality Operator Meaning == equal != not equal

Upload: lindsey-todd

Post on 01-Jan-2016

216 views

Category:

Documents


1 download

TRANSCRIPT

© 2005 Lawrenceville PressSlide 1

Chapter 5Chapter 5

Relational OperatorsRelational OperatorsChapter 5Chapter 5

Relational OperatorsRelational Operators

RelationalOperator Meaning< less than<= less than or equal> greater than>= greater than or equalEqualityOperator Meaning== equal!= not equal

© 2005 Lawrenceville PressSlide 2

Chapter 5Chapter 5

The if StatementThe if StatementChapter 5Chapter 5

The if StatementThe if Statement

Conditional control structure, also called a decision structure

Executes a set of statements when a condition is true

The condition is a Boolean expression

For example, the statementif (x == 5) {

y = 20;}

assigns the value 20 to y only if x is equal to 5.

© 2005 Lawrenceville PressSlide 3

Chapter 5Chapter 5

Roundoff ErrorRoundoff ErrorChapter 5Chapter 5

Roundoff ErrorRoundoff Error

Occurs when a floating point number cannot be exactly represented in binary notation by the computer

Can cause semantic errors in an statement. For example, the condition in the statement

if ((4.80 * 100 - 480) == 0) {System.out.println("Zero.");

}does not evaluate to true because 4.80 can be represented exactly in binary.

© 2005 Lawrenceville PressSlide 4

Comparing ObjectsComparing ObjectsComparing ObjectsComparing Objects

Objects can be tested for equality, but not relationship.Objects can be tested for equality, but not relationship.

x.equals(y)x.equals(y)

Is true if the objects that x and y represent are Is true if the objects that x and y represent are “equal.”“equal.”

Every Java class supports the equals method.Every Java class supports the equals method.

The definition of equals varies from class to class.The definition of equals varies from class to class.

© 2005 Lawrenceville PressSlide 5

String comparisonsString comparisonsString comparisonsString comparisons

Strings are objects, so don’t use == operatorStrings are objects, so don’t use == operator

Use:Use:

str1.compareTo(str2);str1.compareTo(str2);

Returns:Returns:

<0 if str1 < str2<0 if str1 < str2

==0 if str1==str2==0 if str1==str2

>0 if str1 > str2>0 if str1 > str2

© 2005 Lawrenceville PressSlide 6

How Strings really compared…How Strings really compared…How Strings really compared…How Strings really compared…

Java uses Java uses lexicogrpahiclexicogrpahic order order

From the word lexicography – the process of From the word lexicography – the process of compiling a dictionary.compiling a dictionary.

‘‘a’ comes before ‘m’a’ comes before ‘m’

‘‘1’ comes before ‘7’1’ comes before ‘7’

‘ ‘ab’ comes before ‘above’ab’ comes before ‘above’

In the ASCII code ‘1’ comes before ‘A’ which In the ASCII code ‘1’ comes before ‘A’ which comes before ‘a’comes before ‘a’

© 2005 Lawrenceville PressSlide 7

Quick Review!Quick Review!Quick Review!Quick Review!

1.1. To determine whether one number is To determine whether one number is greater than or equal to another, we greater than or equal to another, we would use a ________ type operator.would use a ________ type operator.

2.2. The == and != symbols are called _________ The == and != symbols are called _________ operators.operators.

3.3. Why is it not a good idea to test whether Why is it not a good idea to test whether two doubles are equal?two doubles are equal?

4.4. What method is used to test whether two What method is used to test whether two objects are equal?objects are equal?

5.5. What method is used to test whether two What method is used to test whether two Strings are equal?Strings are equal?

© 2005 Lawrenceville PressSlide 8

Chapter 5Chapter 5

The if-else StatementThe if-else StatementChapter 5Chapter 5

The if-else StatementThe if-else Statement

Contains an else clause that is executed when the if condition evaluates to false. For example, the statement

if (x == 5) {y = 20;

} else {y = 10;

}assigns the value 20 to y if x is equal to 5 or the value 10 if x is not equal to 5.

© 2005 Lawrenceville PressSlide 9

Chapter 5Chapter 5

Nested if-else StatementsNested if-else StatementsChapter 5Chapter 5

Nested if-else StatementsNested if-else Statements

Should be indented to make the logic clear. Nested statement executed only when the

branch it is in is executed. For example, the statement

if (x == 5) {y = 20;

} else {if (x > 5) {

y = 10;} else {

y = 0;}

}evaluates the nested if-else only when x is not equal to 5.

© 2005 Lawrenceville PressSlide 10

Chapter 5Chapter 5

The if-else if StatementThe if-else if StatementChapter 5Chapter 5

The if-else if StatementThe if-else if Statement

Used to decide among three or more actions.

Conditions must be properly ordered for the statement to evaluate as expected. For example, the statement

if (x < 5) {y = 20;

} else if (x < 10) {y = 40;

} else if (x < 15) {y = 80;

} would give very different results if the conditions were ordered differently.

© 2005 Lawrenceville PressSlide 11

Chapter 5Chapter 5

The switch StatementThe switch StatementChapter 5Chapter 5

The switch StatementThe switch Statement Used to decide among three or more actions.

Uses an expression that evaluates to an integer.

The break statement moves program execution to the next statement after the switch.

The default code is optional and is executed when none of the previous cases are met:

switch (numLegs) {case 2: System.out.println("human"); break;case 4: System.out.println("beast"); break;case 8: System.out.println("insect"); break;default: System.out.println("???"); break;

}

© 2005 Lawrenceville PressSlide 12

Chapter 5Chapter 5

The Random ClassThe Random ClassChapter 5Chapter 5

The Random ClassThe Random Class

Part of the java.util package

A Random object can generate random integers (nextInt()) or random floating point numbers (nextDouble()). For example,

Random r = new Random;int numLessThan10;numLessThan10 = r.nextInt(10); //0-9

A random integer in a range is generated by using the formula:

r.nextInt(highNum – lowNum + 1) + lowNum

© 2005 Lawrenceville PressSlide 13

Chapter 5Chapter 5

Compound Boolean ExpressionsCompound Boolean ExpressionsChapter 5Chapter 5

Compound Boolean ExpressionsCompound Boolean Expressions

More than one Boolean expression in a single condition.

Formed using the logical And (&&), logical Or (||), or logical Not (!) operators.

• Precedence: !, &&, ||Precedence: !, &&, ||

© 2005 Lawrenceville PressSlide 14

Chapter 5Chapter 5

And Truth TableAnd Truth TableChapter 5Chapter 5

And Truth TableAnd Truth Table

AndAnd

Exp1Exp1 Exp2Exp2 ResultResult

True True True

True False False

False True False

False False False

© 2005 Lawrenceville PressSlide 15

Chapter 5Chapter 5

Or Truth TableOr Truth TableChapter 5Chapter 5

Or Truth TableOr Truth Table

OrOr

Exp1Exp1 Exp2Exp2 ResultResult

True True True

True False True

False True True

False False False

© 2005 Lawrenceville PressSlide 16

Chapter 5Chapter 5

Not Truth TableNot Truth TableChapter 5Chapter 5

Not Truth TableNot Truth Table

NotNot

ExpExp ResultResult

True False

False True

© 2005 Lawrenceville PressSlide 17

Compiler AmbiguityCompiler AmbiguityCompiler AmbiguityCompiler Ambiguity

a + b * ca + b * c

Could mean:Could mean:

(a + b) * c(a + b) * c

OrOr

a + (b * c)a + (b * c)

Java compiler resolves ambiguity in expressions Java compiler resolves ambiguity in expressions by rules of precedence and associativity.by rules of precedence and associativity.

We know that the correct interpretations of We know that the correct interpretations of a+b*c is…a+b*c is…

© 2005 Lawrenceville PressSlide 18

Okay AP students…Okay AP students…Okay AP students…Okay AP students…

a + (b * c)a + (b * c)

We can force the other interpretation by using

parentheses.

© 2005 Lawrenceville PressSlide 19

Chapter 5Chapter 5

The Math ClassThe Math ClassChapter 5Chapter 5

The Math ClassThe Math Class

Part of the java.lang package

Methods include:

abs(num) returns the absolute value of num

pow(num1, num2) returns num1 raised to the num2 power

sqrt(num) returns the square root of num, where num is a positive number

© 2005 Lawrenceville PressSlide 20

Random NumbersRandom NumbersRandom NumbersRandom NumbersLinear Congruential MethodLinear Congruential Method – Uses a formula to – Uses a formula to

compute the random list of numbers. This method compute the random list of numbers. This method does not produce truly random numbers, because at does not produce truly random numbers, because at some point the numbers repeat.some point the numbers repeat.

In Programming – random numbers are referred to ask In Programming – random numbers are referred to ask pseudorandompseudorandom . .

The Random class resides in the java.util package.The Random class resides in the java.util package.

Some of the random class methods are:Some of the random class methods are:

nextInt( ) nextInt( ) returns the next random integer in the the returns the next random integer in the the random number generator’s sequencerandom number generator’s sequence..

nextInt (n) nextInt (n) returns the next random integer (inclusive) returns the next random integer (inclusive) from 0 to nfrom 0 to n..

nextDouble ( ) nextDouble ( ) returns the next random double from returns the next random double from 0.0 to 1.00.0 to 1.0..

© 2005 Lawrenceville PressSlide 21

Implementation of randomImplementation of randomImplementation of randomImplementation of random import java.util.Random;import java.util.Random;

Public static void main (String[] args) {Public static void main (String[] args) {

Random rnumber = new Random( );Random rnumber = new Random( );

System.out.println(“The first random number System.out.println(“The first random number is :”+r.nextInt(100);is :”+r.nextInt(100);

System.out.println(“The second random number System.out.println(“The second random number is :”+r.nextInt(100);is :”+r.nextInt(100);

}}

© 2005 Lawrenceville PressSlide 22

Chapter 5Chapter 5

Flowchart SymbolsFlowchart SymbolsChapter 5Chapter 5

Flowchart SymbolsFlowchart Symbols

decisiondecision

© 2005 Lawrenceville PressSlide 23

Chapter 5Chapter 5

The RPS FlowchartThe RPS FlowchartChapter 5Chapter 5

The RPS FlowchartThe RPS Flowchart

© 2005 Lawrenceville PressSlide 24

Flowchart decision possibilitiesFlowchart decision possibilitiesFlowchart decision possibilitiesFlowchart decision possibilities

yes no

© 2005 Lawrenceville PressSlide 25

Flowchart decision possibilitiesFlowchart decision possibilitiesFlowchart decision possibilitiesFlowchart decision possibilities

yes no

© 2005 Lawrenceville PressSlide 26

Flowchart decision possibilitiesFlowchart decision possibilitiesFlowchart decision possibilitiesFlowchart decision possibilities

yes

yes

yes

no

no

noCommon exit point

© 2005 Lawrenceville PressSlide 27

HOMEWORKHOMEWORKThe Case of the Dangling The Case of the Dangling ELSEELSE

HOMEWORKHOMEWORKThe Case of the Dangling The Case of the Dangling ELSEELSE

if (n <= max)if (n <= max)

if (n > 0)if (n > 0)

sum += n;sum += n;

elseelse

sum +=max;sum +=max;

--------------------------------------------------------------------------------------------------------------------------

11stst run n = 0; max = 4 run n = 0; max = 4 22ndnd run n=8; max = run n=8; max = 66

What is the value of max after each run?What is the value of max after each run?

DO NOT ASK ME FOR HELP!DO NOT ASK ME FOR HELP!