copyright © 2012 pearson education, inc. lab 8: if statement …. conditionals and loops

27
Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Upload: basil-hubbard

Post on 04-Jan-2016

223 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Copyright © 2012 Pearson Education, Inc.

Lab 8: IF statement ….

Conditionals and Loops

Page 2: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

The if condition Statement

if ( condition ) statement;

if is a Javareserved word

The condition must be aboolean expression. It mustevaluate to either true or false.

If the condition is true, the statement is executed.If it is false, the statement is skipped.

Copyright © 2012 Pearson Education, Inc.

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

Page 3: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Logic of an if statement

conditionevaluated

statement

truefalse

Copyright © 2012 Pearson Education, Inc.

Can use if to code things like:if total > 100

print “$” + total / 100

Page 4: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

The if-else Statement

if ( condition ) statement1;else statement2;

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

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

Copyright © 2012 Pearson Education, Inc.

Page 5: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Logic of an if-else statement

conditionevaluated

statement1

true false

statement2

Copyright © 2012 Pearson Education, Inc.

Can use if to code things like:if total > 100

print “$” + total / 100else

print total + “ cents”

Page 6: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Logic of an if-else statement

total > 100?

print “$” + total / 100

true false

print total + “ cents”

Copyright © 2012 Pearson Education, Inc.

Can use if to code things like:if total > 100

print “$” + total / 100else

print total + “ cents”Boolean expression

Page 7: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Boolean Expressions• A condition often uses one of Java's equality

operators or relational operators, which all return boolean results:

== equal to!= not equal to< less than> greater than<= less than or equal to>= greater than or equal to

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

Copyright © 2012 Pearson Education, Inc.

Page 8: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Created by Emily Hill & Jerry Alan Fails

Logical Operators• What if we wanted to test for multiple conditions?

• For example, what if we want to print the temperature if it’s below 80 degrees and greater than 50 degrees?

• We use logical operators:if (temp < 80 && temp > 50)

System.out.println(temp);

Page 9: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Logical Operators• Boolean expressions can also use the following

logical operators:

! Logical NOT&& Logical AND|| Logical OR

• They all take boolean operands and produce boolean results

• Logical NOT is a unary operator (it operates on one operand)

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

Copyright © 2012 Pearson Education, Inc.

Page 10: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Logical NOT

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

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

• Logical expressions can be shown using a truth table:

Copyright © 2012 Pearson Education, Inc.

a !a

true false

false true

Page 11: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Logical AND and Logical OR• The logical AND expression

a && b

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

• The logical OR expression

a || b

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

Copyright © 2012 Pearson Education, Inc.

Page 12: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Logical AND and Logical OR• A truth table shows all possible true-false

combinations of the terms

• Since && and || each have two operands, there are four possible combinations of conditions a and b

Copyright © 2012 Pearson Education, Inc.

a b a && b a || b

true true true true

true false false true

false true false true

false false false false

Page 13: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Boolean Expressions• Write an expression that evaluates to true if an

integer variable age represents the age of a teenager

(age >= 13 && age <= 19)

Copyright © 2012 Pearson Education, Inc.

Page 14: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Boolean Expressions• Write a statement that prints out “It’s fun to be a

teen” if age represents the age of a teenager

if (age >= 13 && age <= 19)System.out.println(“It’s fun to be a teen”);

if (age > 12 && age < 20)System.out.println(“It’s fun to be a teen”);

Copyright © 2012 Pearson Education, Inc.

Page 15: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Short-Circuited Operators• The processing of && and || is “short-circuited”

• If the left operand is sufficient to determine the result, the right operand is not evaluated

if (count != 0 && total/count > MAX) System.out.println ("Testing.");

• This type of processing is commonly used to avoid divide by zero and null pointer exceptions

Copyright © 2012 Pearson Education, Inc.

Page 16: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Quick Check

Copyright © 2012 Pearson Education, Inc.

What do the following statements do?

if (total != stock + warehouse) inventoryError = true;

if (found || !done) System.out.println("Ok");

Sets the boolean variable to true if the value of totalis not equal to the sum of stock and warehouse

Prints "Ok" if found is true or done is false

Page 17: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Indentation• Indentation is for the human reader, and is ignored

by the compiler

if (depth >= UPPER_LIMIT) delta = 100;else System.out.println("Reseting

Delta"); delta = 0;

• Despite what the indentation implies, delta will be set to 0 no matter what

Copyright © 2012 Pearson Education, Inc.

"Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live."

-- Martin Golding

Page 18: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

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

• Braces can be used to specify the if statement to which an else clause belongs

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

Copyright © 2012 Pearson Education, Inc.

Page 19: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Created by Emily Hill & Jerry Alan Fails

Comparing Data

Page 20: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Comparing Float Values• You might consider two floating point numbers to be

"close enough" even if they aren't exactly equal

• Don’t use == when comparing real numbers(float or double), use a tolerance:

if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal");

• The tolerance could be set to any appropriate level, such as 0.000001 or even 0.01, depending on precision

Copyright © 2012 Pearson Education, Inc.

Page 21: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Comparing Characters• Characters can be compared like numbers, since

internally they are encoded as numbers:

• For example:– ‘a’ + 1 => ‘b’ ‘A’ + 1 => ‘B’

– ‘a’ == ‘a’ => true

Copyright © 2012 Pearson Education, Inc.

Characters Unicode Values

0 – 9 48 through 57

A – Z 65 through 90

a – z 97 through 122

Page 22: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Comparing Strings• Remember a String is an object in Java, so we

cannot use relational operators (==, <, >, etc.) to compare strings (or objects)

• Instead, use the equals method:

• Or compareTo. For example, a call to name1.compareTo(name2)

– returns zero if name1 and name2 are equal (contain the same characters)

– returns a negative value if name1 is less than name2– returns a positive value if name1 is greater than name2

if (name1.equals(name2)) System.out.println ("Same name");

Copyright © 2012 Pearson Education, Inc.

Page 23: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Comparing Objects• When applied to objects, == returns true if the two

references are aliases of each other

• The equals method is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator

• It has been redefined in the String class to compare the characters in the two strings

• When you write a class, you can redefine the equals method to return true under whatever conditions are appropriate

Copyright © 2012 Pearson Education, Inc.

Page 24: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Created by Emily Hill & Jerry Alan Fails

Practice!

Page 25: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Created by Emily Hill & Jerry Alan Fails

Part A: static methods tested in main• Write a method that takes someone’s age as input

and returns true if they can vote but not drink beer. (Note that you must be 18 to vote and 21 to drink.)Test in main

• Write a method isVowel that takes a character as input and returns whether or not the letter is a vowel. Test in main

• Write a method isVowel like above but taking a String as input instead of a character. Test in main

Page 26: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Created by Emily Hill & Jerry Alan Fails

Part B: Timer class• Create a Timer class that counts down from n to 0

(where n is specified by the constructor, 5 by default for the default constructor)

• You will need 2 fields: n & time_left

• Write a tick method that decrements the time left if time left is greater than zero, otherwise it prints: “You have no time left!”

Page 27: Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops

Homework• Finish this lab• Work on CodingBat• Finish Lab 7• Read Chapter 5

Created by Emily Hill & Jerry Alan Fails