27
Decisions, Decisions, Decisions, Decisions, Decisions Decisions Conditional Conditional Statements Statements In Java In Java

Decisions, Decisions, Decisions Conditional Statements In Java

Embed Size (px)

Citation preview

Page 1: Decisions, Decisions, Decisions Conditional Statements In Java

Decisions, Decisions, DecisionsDecisions, Decisions, Decisions

Conditional Conditional StatementsStatements

In JavaIn Java

Page 2: Decisions, Decisions, Decisions Conditional Statements In Java

Conditional Statements in JavaConditional Statements in Java

How would you explain to the Java compiler how to How would you explain to the Java compiler how to do the absolute value function?do the absolute value function? Seems simple enough in mathSeems simple enough in math

All programming languages have some form of All programming languages have some form of decision structure based on logic.decision structure based on logic.

The absolute value logic is:The absolute value logic is: If the value is negative, multiply it by -1If the value is negative, multiply it by -1

In Java it would be written as:In Java it would be written as:if( value < 0 )if( value < 0 )

{{value = -1 * value;value = -1 * value;

}}

Page 3: Decisions, Decisions, Decisions Conditional Statements In Java

The if statementThe if statement

The syntax for an if statement in Java is:The syntax for an if statement in Java is:

if( if( condition condition ))

{{

programming statements…programming statements…

}}

If the If the conditioncondition is true, java begins executing the code is true, java begins executing the code in the {}. Otherwise, the code in the {} is skippedin the {}. Otherwise, the code in the {} is skipped

Note the style!!!Note the style!!!

Indent

Braces line up

Page 4: Decisions, Decisions, Decisions Conditional Statements In Java

Conditional OperatorsConditional OperatorsSymbol in Java Meaning

== Equals

!= Not Equal

< Less Than

<= Less Than or Equal

> Greater Than

>= Greater Than or Equal

Common mistake is to use = (assignment) when you meant == (test if equal)

Page 5: Decisions, Decisions, Decisions Conditional Statements In Java

What will the code print?What will the code print?int testValue = 5;int testValue = 5;if( testValue > 1 )if( testValue > 1 ){{

System.out.println( “The testValue is > 1” );System.out.println( “The testValue is > 1” );}}

System.out.println( “End of Program” );System.out.println( “End of Program” );

The condition, testValue > 1 is trueThe condition, testValue > 1 is true Code in the {} will be executedCode in the {} will be executed This code prints:This code prints:

The testValue is >1The testValue is >1

End of ProgramEnd of Program

Page 6: Decisions, Decisions, Decisions Conditional Statements In Java

What will the code print?What will the code print?

int testValue = 5;int testValue = 5;

if( testValue < 5 )if( testValue < 5 )

{{

System.out.println( “The testValue is < 5” );System.out.println( “The testValue is < 5” );

}}

System.out.println( “End of Program” );System.out.println( “End of Program” );

The condition, testValue > 1 is falseThe condition, testValue > 1 is false Code in the {} will be skippedCode in the {} will be skipped This code prints:This code prints:

End of ProgramEnd of Program

Page 7: Decisions, Decisions, Decisions Conditional Statements In Java

What is the output?What is the output?

Page 8: Decisions, Decisions, Decisions Conditional Statements In Java

Exercises with ifExercises with if Copy and paste the code into a new project called IfTest1:Copy and paste the code into a new project called IfTest1:public class IfTest1public class IfTest1{{

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

System.out.println( “Enter a your age” );System.out.println( “Enter a your age” );Scanner input = new Scanner( System.in );Scanner input = new Scanner( System.in );int age = input.nextInt();int age = input.nextInt();final int LISCENCE_AGE = 16;final int LISCENCE_AGE = 16;if( age >= LISCENCE_AGE )if( age >= LISCENCE_AGE ){{

System.out.println( “You are old enough to get your driver’s license” );System.out.println( “You are old enough to get your driver’s license” );}}System.out.println( “Thank you” );System.out.println( “Thank you” );

}}}}

Run the program and enter some test values.Run the program and enter some test values. Alter the code to print “You are old enough to vote” if the age Alter the code to print “You are old enough to vote” if the age

is greater than or equal to 18is greater than or equal to 18 Alter the code to print “You may pay the child rate” if the age Alter the code to print “You may pay the child rate” if the age

is less than 13is less than 13

Page 9: Decisions, Decisions, Decisions Conditional Statements In Java

if … elseif … else statements statements Another programming feature with decisions is the Another programming feature with decisions is the

if… elseif… else statement statement Suppose you’re charging admission for a theatre and Suppose you’re charging admission for a theatre and

the ticket prices are for children or adults.the ticket prices are for children or adults. Adult: age >= 18Adult: age >= 18 Child: not an adultChild: not an adult

We can write this as the following sentence:We can write this as the following sentence: If age is 18 or higher, charge adult price, If age is 18 or higher, charge adult price, otherwiseotherwise charge charge

child pricechild price The new keyword in our problem is The new keyword in our problem is otherwiseotherwise which which

translates in Java to translates in Java to elseelse

Page 10: Decisions, Decisions, Decisions Conditional Statements In Java

In java the code for the movie theatre is:In java the code for the movie theatre is:final double ADULT_PRICE = 10.75;final double ADULT_PRICE = 10.75;

final double CHILD_PRICE = 8.25;final double CHILD_PRICE = 8.25;

int ticketPrice;int ticketPrice;

if( age >= 18 )//this person is an adultif( age >= 18 )//this person is an adult

{{

ticketPrice = ADULT_PRICE;ticketPrice = ADULT_PRICE;

}}

else//this person is not an adult, therefore a childelse//this person is not an adult, therefore a child

{{

ticketPrice = CHILD_PRICE;ticketPrice = CHILD_PRICE;

}}

System.out.println( “Your ticket price is: “ + ticketPrice );System.out.println( “Your ticket price is: “ + ticketPrice );

if … elseif … else statements statements

Page 11: Decisions, Decisions, Decisions Conditional Statements In Java

The syntax for The syntax for if … else in java is:if … else in java is:if( if( condition condition )){{

programming statements if trueprogramming statements if true}}

elseelse{{

programming statements if falseprogramming statements if false}}

If the original condition is true, then the code in the If the original condition is true, then the code in the {} associated with the {} associated with the ifif statement is executed statement is executed

Otherwise, the code is ignored and the code in the {} Otherwise, the code is ignored and the code in the {} associated with the associated with the elseelse statement is executed statement is executed

if … elseif … else

Page 12: Decisions, Decisions, Decisions Conditional Statements In Java

What Will the Code Print?What Will the Code Print?public class IfElseTestpublic class IfElseTest{{

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

int hoursPastMidNight = 11;int hoursPastMidNight = 11;if( hoursPastMidNight <= 12 )//entered a negative!if( hoursPastMidNight <= 12 )//entered a negative!{{

System.out.println( “It is ” + hoursPastMidNight + “am” );System.out.println( “It is ” + hoursPastMidNight + “am” );}}

elseelse{{

hoursPastMidNight -= 12;//convert to 12 hour time hoursPastMidNight -= 12;//convert to 12 hour time System.out.println( “It is ” + hoursPastMidNight + “pm” );System.out.println( “It is ” + hoursPastMidNight + “pm” );

}}

System.out.println( “End of program” );System.out.println( “End of program” );}}

}}

The first statement is trueThe first statement is true The code in the {} attached to the if is executedThe code in the {} attached to the if is executed The code in the {} attached to the else is ignoredThe code in the {} attached to the else is ignored The result is:The result is:

It is 11amIt is 11amEnd of ProgramEnd of Program

Page 13: Decisions, Decisions, Decisions Conditional Statements In Java

What Will the Code Print?What Will the Code Print?public class IfElseTestpublic class IfElseTest{{

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

int hoursPastMidNight = 21;int hoursPastMidNight = 21;if( hoursPastMidNight <= 12 )//entered a negative!if( hoursPastMidNight <= 12 )//entered a negative!{{

System.out.println( “It is ” + hoursPastMidNight + “am” );System.out.println( “It is ” + hoursPastMidNight + “am” );}}

elseelse{{

hoursPastMidNight -= 12;//convert to 12 hour time hoursPastMidNight -= 12;//convert to 12 hour time System.out.println( “It is ” + hoursPastMidNight + “pm” );System.out.println( “It is ” + hoursPastMidNight + “pm” );

}}

System.out.println( “End of program” );System.out.println( “End of program” );}}

}}

The first statement is falseThe first statement is false The code in the {} attached to the if is ignoredThe code in the {} attached to the if is ignored The code in the {} attached to the else is executedThe code in the {} attached to the else is executed The result is:The result is:

It is 9pmIt is 9pmEnd of ProgramEnd of Program

Page 14: Decisions, Decisions, Decisions Conditional Statements In Java

What is the output?What is the output?

Page 15: Decisions, Decisions, Decisions Conditional Statements In Java

ExampleExample Copy and paste the program into a new projectCopy and paste the program into a new projectpublic class IfElseTestpublic class IfElseTest{{

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

System.out.print( “Please enter a positive integer: “ );System.out.print( “Please enter a positive integer: “ );Scanner input = new Scanner( System.in );Scanner input = new Scanner( System.in );int userInput = input.nextInt();int userInput = input.nextInt();if( userInput < 0 )//entered a negative!if( userInput < 0 )//entered a negative!{{

System.out.println( “I said a POSITIVE!” );System.out.println( “I said a POSITIVE!” );System.out.println( “What’s the matter with you!” );System.out.println( “What’s the matter with you!” );

}}

elseelse{{

System.out.println( “Thank you for following the instructions” );System.out.println( “Thank you for following the instructions” );}}

System.out.println( “End of program” );System.out.println( “End of program” );}}

}}

Compile and run the programCompile and run the program Alter the code to see if a person is old enough to drive, if not, calculate how many Alter the code to see if a person is old enough to drive, if not, calculate how many

years they have to wait and tell them to come back in that many yearsyears they have to wait and tell them to come back in that many years Alter the code to check how many times a person has been late to class this year. Alter the code to check how many times a person has been late to class this year.

Give them a Give them a meanmean message if it’s more than 5 times! message if it’s more than 5 times!

Page 16: Decisions, Decisions, Decisions Conditional Statements In Java

Block StatementsBlock Statements In our class I will always use block statements for conditions and loops.In our class I will always use block statements for conditions and loops. A condition or loop with only one statement in the body does not require a block A condition or loop with only one statement in the body does not require a block

statement:statement: Ex.Ex.

if( age > 16 )if( age > 16 ){{

System.out.println( “You may get your liscence” );System.out.println( “You may get your liscence” );}}

Ex.Ex.if( age > 16 )if( age > 16 )

System.out.println( “You may get your liscence” );System.out.println( “You may get your liscence” );

Can you spot the error?Can you spot the error?

You can omit the block statements if you wish, but it is likely to result in more errorsYou can omit the block statements if you wish, but it is likely to result in more errors

Page 17: Decisions, Decisions, Decisions Conditional Statements In Java

Block StatementsBlock Statements

Another advantage of block statements is clarity.Another advantage of block statements is clarity. Which if does the else belong to?Which if does the else belong to?

If we add braces it is clearer which it belongs toIf we add braces it is clearer which it belongs to

Page 18: Decisions, Decisions, Decisions Conditional Statements In Java

Fixing ErrorsFixing Errors

Page 19: Decisions, Decisions, Decisions Conditional Statements In Java

Fixing ErrorsFixing Errors

Page 20: Decisions, Decisions, Decisions Conditional Statements In Java

Tracing by handTracing by hand

Page 21: Decisions, Decisions, Decisions Conditional Statements In Java

Tracing by handTracing by hand

Page 22: Decisions, Decisions, Decisions Conditional Statements In Java

And finally, And finally, if…else if…elseif…else if…else

What about when there are several conditions What about when there are several conditions that are related?that are related?

In order to ensure that only one statement is In order to ensure that only one statement is executed, we need to chain the executed, we need to chain the if’sif’s together. together.

The next two slides show an example where The next two slides show an example where the limitations of only having the limitations of only having if if are illustrated are illustrated

Page 23: Decisions, Decisions, Decisions Conditional Statements In Java

A Whole Bunch of A Whole Bunch of if’sif’sif( richterScale < 1 )if( richterScale < 1 ){{

System.out.println( “Didn’t even feel it” );System.out.println( “Didn’t even feel it” );}}

if( richterScale < 4 )if( richterScale < 4 ){{

System.out.println( “All my dishes broke :(” );System.out.println( “All my dishes broke :(” );}}

if( richterScale < 7 )if( richterScale < 7 ){{

System.out.println( “Whole lotta shakin going on!” );System.out.println( “Whole lotta shakin going on!” );}}

if( richterScale < 10 )if( richterScale < 10 ){{

System.out.println( “Run for the hills!” );System.out.println( “Run for the hills!” );}} What does the code print if richterScale = 8?What does the code print if richterScale = 8?

Run for the hills!Run for the hills! What does the code print if richterScale = 5?What does the code print if richterScale = 5?

Whole lotta shakin going on!Whole lotta shakin going on!Run for the hills!Run for the hills!

True

False

False

False

True

Page 24: Decisions, Decisions, Decisions Conditional Statements In Java

Fixing the previous exampleFixing the previous exampleif( richterScale < 1 )if( richterScale < 1 ){{

System.out.println( “Didn’t even feel it” );System.out.println( “Didn’t even feel it” );}}

else if( richterScale < 4 )else if( richterScale < 4 ){{

System.out.println( “All my dishes broke :(” );System.out.println( “All my dishes broke :(” );}}

else if( richterScale < 7 )else if( richterScale < 7 ){{

System.out.println( “Whole lotta shakin going on!” );System.out.println( “Whole lotta shakin going on!” );}}

else else {{

System.out.println( “Run for the hills!” );System.out.println( “Run for the hills!” );}} What does the code print if richterScale = 8?What does the code print if richterScale = 8?

Run for the hills!Run for the hills! What does the code print if richterScale = 5?What does the code print if richterScale = 5?

Whole lotta shakin going on!Whole lotta shakin going on!

True, ignore anything else in the group

False

False

False

No if’s were true, so automatically go here

Page 25: Decisions, Decisions, Decisions Conditional Statements In Java

if...else if…elseif...else if…else

Java evaluates EVERY Java evaluates EVERY ifif statement. statement. The only exception is when they are joined by The only exception is when they are joined by

the reserved word the reserved word elseelse Java evaluates a sequence of Java evaluates a sequence of if/else if/elseif/else if/else

statements until the FIRST one is true.statements until the FIRST one is true. If none are true then the If none are true then the elseelse is evaluated is evaluated Only one set of statements in the group will be Only one set of statements in the group will be

evaluatedevaluated

Page 26: Decisions, Decisions, Decisions Conditional Statements In Java

if...else if…else if...else if…else syntaxsyntaxif( if( condition condition )){{

statements if truestatements if true}}

else if( else if( condition condition )){{

statements if truestatements if true}}…………else if( else if( condition condition )){{

statements if truestatements if true}}

elseelse{{

statements if all others in the group were falsestatements if all others in the group were false}}

Page 27: Decisions, Decisions, Decisions Conditional Statements In Java

What is Printed?What is Printed?int age = 21;int age = 21;

if( age <= 12 )//12 or youngerif( age <= 12 )//12 or younger{{

System.out.println( "Your cost is $5.50" );System.out.println( "Your cost is $5.50" );}}

else if( age <=19 ) //older than 12 but 19 or youngerelse if( age <=19 ) //older than 12 but 19 or younger{{

System.out.println( "Your cost is $8.25" );System.out.println( "Your cost is $8.25" );}}

else if( age <= 64 ) //older than 19 but 64 or youngerelse if( age <= 64 ) //older than 19 but 64 or younger{{

System.out.println( "Your cost is $13.75" );System.out.println( "Your cost is $13.75" );}}

else //older than 64else //older than 64{{

System.out.println( "Your cost is $5.50" );System.out.println( "Your cost is $5.50" );}} Your cost is $13.75Your cost is $13.75

False

False

True, everything else below ignored