58
Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Embed Size (px)

Citation preview

Page 1: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Decisions: Handling Infinite

CasesCS 21a: Introduction to

Computing IFirst Semester, 2013-2014

Page 2: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Previously…

►Modularity with procedures and OOP►Generality with variables

Page 3: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Next Set of Lectures…

►Generality with conditionals► For dealing with infinite test cases (when

simple variables and expressions won’t work)

►Generality with loops► For dealing with infinite (or arbitrary

length) processes

►Generality with arrays► For dealing with infinite (or arbitrary-

sized) data

Page 4: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Conditional Execution

►Sometimes a simple, linear, clean formula is enough to solve a general problem.

►Sometimes we need to branch because we are forced to handle some subsets of the input cases slightly differently.

Page 5: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Conditional Execution

►Java structures for conditions►The if-statement►boolean variables, operators,

expressions, and methods►The ? Operator►The switch-statement

Page 6: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

The if Statement

►Syntaxif (condition)

statement►Notes►parentheses are required around the

condition►statement means any valid statement

in Java (including if-statements and blocks)

Page 7: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Example 1public class BankAccount{ private double balance; ... public void withdraw( double amount ) { if ( amount <= balance ) balance = balance - amount; System.out.println( "End of Transaction" ); // print statement executed unconditionally } ...}

Page 8: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Example 2public class BankAccount{ private double balance; ... public void withdraw( double amount ) { if ( amount <= balance ) balance = balance - amount; if ( amount > balance )

balance = balance – OVERDRAFT_PENALTY; } ...}

Page 9: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

The Optional else Clause

►If-statement syntax revisitedif (condition) statementelse statement

►Use whenever an alternative statement should be executed when the condition is not met

Page 10: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Example 2, revised: Using the else

public class BankAccount{ private double balance; ... public void withdraw( double amount ) { if ( amount <= balance ) balance = balance - amount; else

balance = balance – OVERDRAFT_PENALTY; } ...}

Page 11: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Example 3public class BankAccount

{

private double balance;

...

public void withdraw( double amount )

{

if ( amount <= balance )

balance = balance - amount;

else

System.out.println( "Insufficient Balance" );

System.out.println( "End of Transaction" );

}

...

}

No penalty is appliedbut an error messageis printed when thecondition is not met

Page 12: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Example 4

►Suppose two statements need to be conditionally executed

►Incorrect attemptif ( amount <= balance )

balance = balance - amount;

System.out.println("amount deducted");

►Print statement will be executed unconditionally

Page 13: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Block of Statements

►A block allows us to group several statements into one► place the statements in sequence and

surround them with { }►Correct code

if ( amount <= balance )

{

balance = balance - amount;

System.out.println("amount deducted");

}

Page 14: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Brace Layout, White Spaces,and Indentation

► In Java, spaces, tabs, and extra lines don't affect the meaning of the program

►A program could be written in diff ways; e.g.,► all in one line► such that each word/symbol is in one line► such that words/symbols are separated by

5 spaces each►BUT … Spaces (indentation) help to

clarify intent

Page 15: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Brace Layout

if (amount <= balance){double newBalance = balance – amount;balance = newBalance;

}OR

if (amount <= balance) {double newBalance = balance – amount;balance = newBalance;

}

Page 16: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Indentation and Tabspublic class BankAccount{ private double balance; ... public void withdraw( double amount ) { if ( amount <= balance )` balance = balance - amount; else

balance = balance – OVERDRAFT_PENALTY; } ...}

Two to three spaces per indentation

Page 17: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Indentation and Tabspublic class BankAccount{ private double balance; ... public void withdraw( double amount )

{ if ( amount <= balance ) balance = balance - amount; else

balance = balance – OVERDRAFT_PENALTY;

} ...}

Eight spaces per indentation

Page 18: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Relational Operators

►Compares two (usually numeric) operands

►>, >=, <, <=, == (equal), != (not equal)►Example: >=

► binary operation► returns a boolean result

►true if left operand is greater than or equal to right operand

► false otherwise

Page 19: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Practice Programming Problem

►Implement an absolute value function.

Page 20: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Comparing Floating-Point Numbers

► Consider this code:double r = Math.sqrt(2); double d = r * r - 2; if (d == 0) System.out.println(

"sqrt(2)squared minus 2 is 0" ); else System.out.println(

"sqrt(2)squared minus 2 is not 0 but " + d );

► It prints:sqrt(2)squared minus 2 is not 0but 4.440892098500626E-16

Page 21: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Comparing Floating-Point Numbers

►To avoid round-off errors, don't use == to compare floating-point numbers

►To compare floating-point numbers, test whether they are close enough: |x - y| ≤ ε final double EPSILON = 1E-14;

if (Math.abs(x - y) <= EPSILON)

// x is approximately equal to y

►ε is a small number such as 10-14

Page 22: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Comparing Strings

►Don't use == for strings! if (input == "Y") // WRONG!!!

►Use equals method: if (input.equals("Y"))

►== tests identity, equals() tests forequal contents

►Case insensitive test ("Y" or "y") if (input.equalsIgnoreCase("Y"))

Page 23: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Comparing Strings

►s.compareTo(t) < 0 means:s comes before t in the dictionary

►"car" comes before "cargo" ►All uppercase letters come before

lowercase: "Hello" comes before "car"

Page 24: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Lexicographic Comparison

Page 25: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Practice Programming Problem

►Write a program that reads two words and says if they have the SAME or DIFFERENT starting letter.

►Sample InputCar carrot

►Sample OutputSAME

Page 26: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Comparing Objects

►Since object variables contain references,== tests for identity,not for identical object content

►BankAccount b = new BankAccount( 1000 );BankAccount c = new BankAccount( 1000 );

►Object references are not the same► b != c

►But contents are equal► b.getBalance() == c.getBalance()

Page 27: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Testing for Null► null reference refers means no object

String middleInitial = null; // not setif (…) middleInitial = middleName.substring(0, 1);

► Can be used in tests:if (middleInitial == null) System.out.println(firstName + " " + lastName);else System.out.println(firstName + " " + middleInitial + ". " + lastName);

► Use ==, not equals(), to test for null ► Note that null is not the same as the empty string

""

Page 28: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Sequences of Comparisons

►The statementthat correspondsto the first matching conditionis executed

►Also called anif-else chain

if (condition1)

statement1;

else if (condition2)

statement2;

. . .

else

statement;

Page 29: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Example 5

if ( score >= 92 ) System.out.println( "A" );else if ( score >= 80 ) System.out.println( "B" );else if ( score >= 70 ) System.out.println( "C" );else if ( score >= 60 ) System.out.println( "D" );else System.out.println( "F" );

Page 30: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

About the if-else Chain

►Order matters► if (score >= 60)

System.out.println( "D" );else if (score >= 70) System.out.println( "C" );…// most students will get D's

►See Richter's scale example in the textbook for another if-else chain

►The if-else chain is an example of a nested branch

Page 31: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Practice Programming Problem

►Write a program that reads two numbers and tells if the first is bigger, smaller, or equal to the second one. Print out the absolute difference if they’re not equal.

►Sample Input1 2

►Sample Outputsmaller by 1

Page 32: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Nested Branches

►Branch inside another branchif (condition0) if (condition1) statement1a; else statement1b; else statement2;

else portion couldalso contain anested branch; e.g., if (condition2) statement2a; else statement2b;

Page 33: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Example 6

►Movie ticket price example►Premium movie (first week of

release): P120►Regular movie (second week of

release or later): P100►Senior citizen discount: 20%

Page 34: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Example 6public double TicketPrice( int customerAge, int daysShowing ){

double cost;

if (customerAge >= 60)if ( daysShowing < 8 ) cost = 120.0 * 0.80;

else cost = 100.0 * 0.80;

elseif ( daysShowing < 8 ) cost = 120.0;

else cost = 100.0;

return cost; }

Page 35: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

The boolean Data Type

►Only two possible values►true and false

►Literals►true, false► lowercase (reserved words in Java)

►Operations► relational operators► logical operators

Page 36: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Logical Operators

►Boolean operands►&& (and), || (or), ! (unary not)►Example

((x>=0) && (x<=9))

►Truth table depicts semantics of the operation►similar to a multiplication/addition

table

Page 37: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

! (NOT)

►Unary operation►Returns a boolean result► true when the operand is false► false when the operand is true

►Example►alternative to !=► (a != 5) same as (!(a == 5))

Page 38: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

&& (AND)

►Returns a boolean result► true whenever both

operands are true► false otherwise

►Example:► testing whether a

number is between 0 and 9

► if ((num >= 0) && (num <= 9)) ... // inclusive

►Truth Table?

A B A && B

False

False

False

False

True False

True False

False

True True True

Page 39: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

|| (OR)

►Returns a boolean result► true when at least one operand

is true► false otherwise

►Example► if ((num % 2 == 0) || (num % 3 == 0)) …

► condition will evaluate to true if the number is a even or if it is a multiple of 3

►Truth Table?

A B A || B

False

False

False

False

True True

True False

True

True True True

Page 40: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Short-Circuit Evaluation

► Sometimes, we know the result of a boolean expression without checking all the conditions

► AND (&&): If first condition is false, then result is false regardless of second condition

( x < y ) && ( a < b )

► OR (||): If first condition is true, then result is true regardless of second condition

( x < y ) || ( a < b )

► Short-circuit evaluation can prevent errors( x < 0 ) || ( Math.sqrt( x ) > 20 )

( x != 0 ) && ( y/x > 20 )

Page 41: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Practice Programming Problem

►Write a program that reads three different numbers and tells if they are in INCREASING order, DECREASING

order, or UNSORTED.

►Sample Input1 3 9

►Sample OutputINCREASING

Page 42: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

boolean Variables

►Boolean variables are convenient for long conditions

►Exampleboolean withinRange;

withinRange = ( num >= 0 ) && ( num <= 9 );

if ( withinRange ) ...

Page 43: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Methods with boolean Return Values

►Methods can return boolean-type values

►Allows you to encapsulate complex conditions, or conditions that depend on the state of an object

Page 44: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Example 7public class BankAccount

{

...

public static final int MINBAL = 10000;

...

public boolean isBelowMinBalance()

{

if ( balance < MINBAL )

return true;

else

return false;

}...

}

It is common and recommended practice to give boolean-type methods names starting with isXXX

Is there a shorter way to write this?

Page 45: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Example 7, revised

public class BankAccount

{

...

public static final int MINBAL = 10000;

...

public boolean isBelowMinBalance()

{

return (balance < MINBAL);

}

...

}

Page 46: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Calling a boolean-type Method

public class BankSystem

{

public static void main( String args[] )

{

BankAccount b = new BankAccount();

...

boolean below = b.isBelowMinBalance();

if ( below )

System.out.println( "account is below balance" );

else

System.out.println( "account is OK" );

...

}

}

Page 47: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Calling a boolean-type Method within the Same Class

public class BankAccount

{ ...

public void withdraw( double amount )

{

if ( amount <= balance )

{

balance = balance - amount;

if ( isBelowMinBalance() )

balance = balance – 50; // subtract penalty

}

else

System.out.println( "Insufficient Balance" );

} ...

}

Page 48: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Advanced Topics

►Dangling Else►The ? operator►The switch statement

Page 49: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Dangling else

if ( num > 10 ) if ( num > 100 ) System.out.println( "Large" );else System.out.println( "Small" );

►What gets printed out when num = 150? when num = 80? when num = 5?

►Which if does the else clause match?

Page 50: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Dangling else

►Rule in Java: an else clause matches the nearest enclosing if

►Use { } to match the outer ifif ( num > 10 ) { if ( num > 100 ) System.out.println( "Large" );}else System.out.println( "Small" );

Page 51: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

The ? operator► Syntax: condition ? then-value : else-value► Use this as a one-line replacement for if► Instead of

String s;if ( x % 2 == 0 ) s = "even";else s = "odd";

► We can sayString s = (x%2 == 0) ? "even" : "odd";

► Commonly used in C programs► Use sparingly, since it can lead to cryptic code

Page 52: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

The if-else Chain Revisited

►If the conditions in an if-else chain are exact comparisons (using ==) on integral (or char) values, consider using a switch statement

►Example: print "One" if the value is 1,print "Two" if the value if 2, …

Page 53: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Example 8if (num == 1)

{

System.out.println("One");

}

else if (num == 2)

{

System.out.println("Two");

}

else if (num == 3)

{

System.out.println("Three");

}

else

{

System.out.println("Other number");

}

Page 54: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Example 8, revised;Using a Switch

switch(num)

{

case 1:

System.out.println("One");

break;

case 2:

System.out.println("Two");

break;

case 3:

System.out.println("Three");

break;

default:

System.out.println("Other number");

}

Page 55: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

The switch Statement► Use a switch statement whenever

► the conditions in an if-else chain are designed to check for constant values representing a finite number of cases

► Switch-case statement► switch( exp )

► exp must be a "countable" primitive type (i.e., byte, int, char, etc., but not float or double)

► NEW TO JAVA 7: or a String (not allowed in older versions of Java)

► case literal ► serves as "entry-point" label for case when exp==literal

► break;► statement that causes control to exit the block► if there's no break, control "falls-through" until we see a break

Page 56: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Using (or not using) breakswitch( letter ) { case 'a': case 'e': case 'i': case 'o': case 'u': System.out.println("Vowel"); break; default: System.out.println("Consonant");}

Page 57: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Summary

► A program will sometimes need to branch.► Branches often rely on testing if the input

satisfies some condition.► Branches are specified with conditionals.► Conditions are specified with boolean

expressions.► There are several kinds of conditionals in

Java. Learn to choose the most appropriate for the problem at hand.

Page 58: Decisions: Handling Infinite Cases CS 21a: Introduction to Computing I First Semester, 2013-2014

Next Time…

►Loops, or finite algorithms for infinite processes.