46
Boolean expressions Boolean expressions Conditional statements Conditional statements and expressions and expressions

Boolean expressions Conditional statements and expressions

Embed Size (px)

Citation preview

Boolean expressionsBoolean expressionsConditional statements and Conditional statements and

expressionsexpressions

Penny guessing gamePenny guessing game

I weighed a pound of pennies and found I weighed a pound of pennies and found there was exactly 160.there was exactly 160.

160 is an integer.160 is an integer.int exact = 160;int exact = 160;

But nothing stops me from changing it.But nothing stops me from changing it. It is also a constant that I never want to It is also a constant that I never want to

change.change.finalfinal int exact = 160; int exact = 160;

So let’s write a guessing game.So let’s write a guessing game.

Penny guessing gamePenny guessing gameimport java.util.Scanner;import java.util.Scanner;

public class GuessingGame {public class GuessingGame {public static void main ( String s[] ) {public static void main ( String s[] ) {

final int exact = 160;final int exact = 160;Scanner in = new Scanner( System.in );Scanner in = new Scanner( System.in );//prompt for a guess//prompt for a guessSystem.out.print( “Guess the # of pennies in a pound. “ );System.out.print( “Guess the # of pennies in a pound. “ );int guess = in.nextInt();int guess = in.nextInt();//check the answer//check the answer// If guess and exact are equal, then let them know.// If guess and exact are equal, then let them know.// Otherwise, let them know that their guess was incorrect.// Otherwise, let them know that their guess was incorrect.

(We currently don’t have the language tools to do this!)(We currently don’t have the language tools to do this!)

in.close();in.close();}}

}}

Penny guessing gamePenny guessing gameimport java.util.Scanner;import java.util.Scanner;

public class GuessingGame {public class GuessingGame {public static void main ( String s[] ) {public static void main ( String s[] ) {

final int exact = 160;final int exact = 160;Scanner in = new Scanner( System.in );Scanner in = new Scanner( System.in );//prompt for a guess//prompt for a guessSystem.out.print( “Guess the # of pennies in a pound. “ );System.out.print( “Guess the # of pennies in a pound. “ );int guess = in.nextInt();int guess = in.nextInt();//check the answer//check the answerif (guess==exact)if (guess==exact) System.out.println( “You are correct!” );System.out.println( “You are correct!” );elseelse System.out.println( “Nope.” );System.out.println( “Nope.” );

in.close();in.close();}}

}}

Penny guessing gamePenny guessing game

……//check the answer//check the answerif (guess==exact)if (guess==exact) System.out.println( “You are correct!” );System.out.println( “You are correct!” );elseelse System.out.println( “Nope.” );System.out.println( “Nope.” );……

== is a boolean (true or false) operator== is a boolean (true or false) operator It tests for equality.It tests for equality.

A==B is a boolean expressionA==B is a boolean expression The result of this expression is either true or false.The result of this expression is either true or false.

George BooleGeorge Boole

2 November 1815 – 8 2 November 1815 – 8 December 1864December 1864

an English mathematician an English mathematician and philosopherand philosopher

As the inventor of Boolean As the inventor of Boolean logic—the basis of modern logic—the basis of modern digital computer logic—digital computer logic—Boole is regarded in Boole is regarded in hindsight as a founder of hindsight as a founder of the field of computer the field of computer science.science.

Penny guessing gamePenny guessing game

Let’s accept a guess that’s 160 Let’s accept a guess that’s 160 ±± 10%. 10%.

Penny guessing gamePenny guessing game

Let’s accept a guess that’s 160 Let’s accept a guess that’s 160 ±± 10%. 10%.So let’s define two more constants – the So let’s define two more constants – the

minimum and the maximum that we’ll minimum and the maximum that we’ll accept.accept.

Penny guessing gamePenny guessing game

Let’s accept a guess that’s 160 Let’s accept a guess that’s 160 ±± 10%. 10%.So let’s define two more constants – the So let’s define two more constants – the

minimum and the maximum that we’ll minimum and the maximum that we’ll accept.accept.final int exact = 160;final int exact = 160;

final int max = exact + exact/10;final int max = exact + exact/10;

final int min = exact - exact/10;final int min = exact - exact/10;

Penny guessing gamePenny guessing game

Now we must change the check to include the Now we must change the check to include the acceptable range.acceptable range.

……

//check the answer//check the answer

if (guess==exact)if (guess==exact)

System.out.println( “You are correct!” );System.out.println( “You are correct!” );

elseelse

System.out.println( “Nope.” );System.out.println( “Nope.” );

……

Penny guessing gamePenny guessing game Now we must change the check to include the acceptable Now we must change the check to include the acceptable

range.range.……//check the answer//check the answerif (guess==exact)if (guess==exact) System.out.println( “You are correct!” );System.out.println( “You are correct!” );else if (guess<min)else if (guess<min) System.out.println( “Nope.” );System.out.println( “Nope.” );else if (guess>max)else if (guess>max) System.out.println( “Nope.” );System.out.println( “Nope.” );elseelse System.out.println( “Close enough.” );System.out.println( “Close enough.” );……

Penny guessing gamePenny guessing game

……//check the answer//check the answerif (guess==exact)if (guess==exact) System.out.println( “You are correct!” );System.out.println( “You are correct!” );else if (guess<min)else if (guess<min) System.out.println( “Nope.” );System.out.println( “Nope.” );else if (guess>max)else if (guess>max) System.out.println( “Nope.” );System.out.println( “Nope.” );elseelse System.out.println( “Close enough.” );System.out.println( “Close enough.” );……

Note that we write “Nope.” if the first boolean expression or the second boolean expression is true.

Wouldn’t it be nice if we had a boolean operator for or?

Penny guessing gamePenny guessing game

……

//check the answer//check the answer

if (guess==exact)if (guess==exact)

System.out.println( “You are correct!” );System.out.println( “You are correct!” );

else if (guess<min | guess>max)else if (guess<min | guess>max)

System.out.println( “Nope.” );System.out.println( “Nope.” );

elseelse

System.out.println( “Close enough.” );System.out.println( “Close enough.” );

……

boolean operator for or

Penny guessing gamePenny guessing game

……

//check the answer//check the answer

if (guess==exact)if (guess==exact)

System.out.println( “You are correct!” );System.out.println( “You are correct!” );

else if (else if (guess>=min & guess<=maxguess>=min & guess<=max))

System.out.println( “System.out.println( “Close enough.Close enough.” );” );

elseelse

System.out.println( “System.out.println( “Nope.Nope.” );” );

……

boolean operator for and

Operators used in boolean Operators used in boolean expressionsexpressions

Unary (i.e., op A):Unary (i.e., op A): !! notnot

Binary (i.e., A op B):Binary (i.e., A op B): <, >, <=, >=<, >, <=, >= lt, gt, le, gelt, gt, le, ge ==, !===, != equals, not equalequals, not equal && andand || oror &&&& andand |||| oror

This is also the precedence from highest to lowest.This is also the precedence from highest to lowest.

Truth table for ANDTruth table for AND

A & B AT F

B T T FF F F

Truth table for ORTruth table for OR

A | B AT F

B T T TF T F

Truth table for NOTTruth table for NOT

!A AT FF T

COMPARING STRINGSCOMPARING STRINGS

Comparing stringsComparing strings

== doesn’t work (as you expect) so please == doesn’t work (as you expect) so please don’t use it for comparing strings. (But use don’t use it for comparing strings. (But use == for comparing ints or doubles.)== for comparing ints or doubles.)

Example:Example:String city1 = “Philadelphia”;String city1 = “Philadelphia”;

String city2 = “Phoenix”;String city2 = “Phoenix”; I want to say:I want to say:

if (city1==city2)if (city1==city2) but I can’t!but I can’t!

Comparing stringsComparing strings

Use .equals() instead:Use .equals() instead:

if (city1.equals(city2)) …if (city1.equals(city2)) …

.equals() is case sensitive (i.e., NYC is not .equals() is case sensitive (i.e., NYC is not the same as NyC)the same as NyC)

.equalsIgnoreCase() is not case sensitive.equalsIgnoreCase() is not case sensitive

if (city1.equalsIgnoreCase(city2)) …if (city1.equalsIgnoreCase(city2)) …

if’s and blocksif’s and blocks

Sometimes we wish to execute more than one Sometimes we wish to execute more than one statement for an statement for an ifif statement. statement.if (x==y)if (x==y)

singleStatement;singleStatement;

if (x==y) if (x==y) {{

statement1;statement1;

statement2;statement2;

……

statementn;statementn;

}}

{

s1;

s2;

sn;

}

This is called a block.

if’s and blocksif’s and blocks

Common mistake: Are the following all the Common mistake: Are the following all the same (or are they different)?same (or are they different)?

if (x==y)System.out.println( "hello" );

System.out.println( "there" );

if (x==y)System.out.println( "hello" );

System.out.println( "there" );

if’s and blocksif’s and blocks

Common mistake: Are the following all the Common mistake: Are the following all the same (or are they different)?same (or are they different)?

if (x==y)System.out.println( "hello" );

System.out.println( "there" );

if (x==y) {System.out.println( "hello" );

System.out.println( "there" );}

if’s and blocksif’s and blocks

Common mistake: Are the following all the Common mistake: Are the following all the same (or are they different)?same (or are they different)?

if (x==y) {System.out.println( "hello" );

System.out.println( "there" );}

if (x==y) {System.out.println( "hello" );

System.out.println( "there" );}

if’s and blocksif’s and blocks

Common mistake: Are the following all the Common mistake: Are the following all the same (or are they different)?same (or are they different)?

if (x==y) {System.out.println( "hello" );

}System.out.println( "there" );

if (x==y) {System.out.println( "hello" );

}System.out.println( "there" );

if‘s and blocksif‘s and blocks

Rule(s):Rule(s):Don’t be confused/misled by indentation!Don’t be confused/misled by indentation!The purpose of indentation is to make code The purpose of indentation is to make code

more more humanlyhumanly readable. readable. Indentation does not matter to the compiler at Indentation does not matter to the compiler at

all.all.Blocks (not indentation) group lines of code Blocks (not indentation) group lines of code

together.together.

if examplesif examples

if (x == 2 & y < 10)if (x == 2 & y < 10)x = 10;x = 10;

if (x == 2) {if (x == 2) {x = 10;x = 10;

}}

if (x == y) {if (x == y) {x = 0;x = 0;y = 1;y = 1;

}}

if examplesif examples

if (x==y) {if (x==y) {

x = 0;x = 0;

y = 1;y = 1;

} else {} else {

x = 1;x = 1;

y = 0;y = 0;

}}

if examplesif examples

if (x==1) {if (x==1) {x = 2;x = 2;y = 3;y = 3;

} else if (x==2) {} else if (x==2) {x = 3;x = 3;y = 4;y = 4;

} else {} else {x = 1;x = 1;y = 0;y = 0;

}}

if examplesif examples

if (x==1) {if (x==1) {x = 2;x = 2;y = 3;y = 3;

} else if (x==2) {} else if (x==2) {x = 3;x = 3;y = 4;y = 4;

} else { //we don’t need to restate } else { //we don’t need to restate else if (x!=1 && x!=2)else if (x!=1 && x!=2)

x = 1;x = 1;y = 0;y = 0;

}}

if-else form in generalif-else form in general

if (conds1)if (conds1)one-statement; or { block-of-statements }one-statement; or { block-of-statements }

else if (conds2)else if (conds2)one-statement; or { block-of-statements }one-statement; or { block-of-statements }

……else if (condsn)else if (condsn)

one-statement; or { block-of-statements }one-statement; or { block-of-statements }elseelse

one-statement; or { block-of-statements }one-statement; or { block-of-statements }

if-else formif-else form

Same or different?Same or different?

int x = 5;

if (x >= 4)System.out.println( "A" );

if (x >=5)System.out.println( "B" );

int x = 5;

if (x >= 4)System.out.println( "A" );

else if (x >=5)System.out.println( "B" );

if-else formif-else form

Same or different?Same or different?

int x = 5;

if (x >= 4) {System.out.println( "A" );

} else if (x >=5) {System.out.println( "B" );

}

int x = 5;

if (x >= 4)System.out.println( "A" );

else if (x >=5)System.out.println( "B" );

if-else formif-else form

Same or different?Same or different?int x = 5;

if (x >= 4) {System.out.println( "A" );

} else if (x >=5) {System.out.println( "B" );

}

int x = 5;

if (x >= 4){

System.out.println( "A" );}else if (x >=5){

System.out.println( "B" );}

Boolean type, and boolean Boolean type, and boolean variablesvariables

boolean b;boolean b;b = true;b = true;b = false;b = false;

int x = 10;int x = 10;int y = 9;int y = 9;b = (x==y);b = (x==y);b = (x>y);b = (x>y);

Boolean I/OBoolean I/O

boolean answer = in.nextBoolean();boolean answer = in.nextBoolean();You must type in either You must type in either truetrue or or falsefalse and hit and hit

return (enter).return (enter).

System.out.println( answer );System.out.println( answer ); //works as too //works as too

Conditional operator ?:Conditional operator ?:

Many programs contain code like the Many programs contain code like the following:following:

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

average = sum / n;average = sum / n;

elseelse

average = 0;average = 0;

Conditional operator ?: exampleConditional operator ?: example

Many programs contain code like the following:Many programs contain code like the following:

int apples = 6;int apples = 6;

if (apples != 1)if (apples != 1)

System.out.printf( "I have %d apples. \n", apples );System.out.printf( "I have %d apples. \n", apples );

elseelse

System.out.printf( "I have %d apple. \n", apples );System.out.printf( "I have %d apple. \n", apples );

int apples = 6;if (apples != 1)

System.out.println( "I have " + apples + " apples." );else

System.out.println( "I have " + apples + " apple." );

(examples use printf and println)

Conditional operator ?:Conditional operator ?:

(boolean-expr) ? expr(boolean-expr) ? exprif-trueif-true : expr : exprif-falseif-false

evaluated if-and-only-if (iff) boolean-expr is true

evaluated iff boolean-expr is false

Conditional operator ?:Conditional operator ?:

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

average = sum / n;average = sum / n;

elseelse

average = 0;average = 0;

average = (n > 0) ? sum / n : 0;average = (n > 0) ? sum / n : 0;

Conditional operator ?: Conditional operator ?: (example using printf)(example using printf)

int apples = 6;int apples = 6;

if (apples != 1)if (apples != 1)

System.out.printf( "I have %d apples \n", apples );System.out.printf( "I have %d apples \n", apples );

elseelse

System.out.printf( "I have %d apple \n", apples );System.out.printf( "I have %d apple \n", apples );

System.out.printf( "I have %d apple%s \n", apples,System.out.printf( "I have %d apple%s \n", apples,

(apples != 1) ? "s" : "" );(apples != 1) ? "s" : "" );

Conditional operator ?: Conditional operator ?: (example using println)(example using println)

int apples = 6;int apples = 6;

if (apples != 1)if (apples != 1)

System.out.println( "I have " + apples + " apples." );System.out.println( "I have " + apples + " apples." );

elseelse

System.out.println( "I have " + apples + " apple." );System.out.println( "I have " + apples + " apple." );

System.out.printf( "I have " + apples + " apple"System.out.printf( "I have " + apples + " apple"

+ (apples != 1) ? "s" : ""+ (apples != 1) ? "s" : ""

+ "." );+ "." );

Conditional operator ?:Conditional operator ?:

Problem: We have 2 int’s, A and B. We Problem: We have 2 int’s, A and B. We want another int, C, to be set to the want another int, C, to be set to the maximum of A and B.maximum of A and B.

How can we do this with if-else?How can we do this with if-else?

How can we do this with How can we do this with ?:?:??

Conditional operator ?:Conditional operator ?:

Problem: We have 2 int’s, A and B. We Problem: We have 2 int’s, A and B. We want another int, C, to be set to the want another int, C, to be set to the maximum of A and B.maximum of A and B.How can we do this with if-else?How can we do this with if-else?

if (A>B)if (A>B)

C = A;C = A;

elseelse

C = B;C = B;

How can we do this with How can we do this with ?:?:??

Conditional operator ?:Conditional operator ?:

Problem: We have 2 int’s, A and B. We Problem: We have 2 int’s, A and B. We want another int, C, to be set to the want another int, C, to be set to the maximum of A and B.maximum of A and B.How can we do this with if-else?How can we do this with if-else?

if (A>B)if (A>B)

C = A;C = A;

elseelse

C = B;C = B;How can we do this with How can we do this with ?:?:??

C = (A>B) ? A : B;C = (A>B) ? A : B;