Decisions, Decisions, Decisions Conditional Statements In Java.

Slides:



Advertisements
Similar presentations
Flow of Control Usually the order of statement execution through a method is linear: one after another flow of control: the order statements are executed.
Advertisements

Logic & program control part 3: Compound selection structures.
3 Decision Making: Equality and Relational Operators A condition is an expression that can be either true or false. Conditions can be formed using the.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
1 Control Structures (and user input). 2 Flow of Control The order statements are executed is called flow of control By default, statements in a method.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
Conditions What if?. Flow of Control The order of statement execution is called the flow of control Unless specified otherwise, the order of statement.
Introduction to Computers and Programming Lecture 10: For Loops Professor: Evan Korth New York University.
Introduction to Computers and Programming Lecture 5 Boolean type; if statement Professor: Evan Korth New York University.
ECE122 L7: Conditional Statements February 20, 2007 ECE 122 Engineering Problem Solving with Java Lecture 7 Conditional Statements.
Introduction to Computer Programming Decisions, Decisions: Boolean Expressions and Selection.
Relational Operators Control structures Decisions using “if” statements  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Boolean Expressions and If Flow of Control / Conditional Statements The if Statement Logical Operators The else Clause Block statements Nested if statements.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
Chapter 5 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/33 Conditionals and Loops Now we will examine programming statements.
CSC 1051 M.A. Papalaskari, Villanova University Repetition CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing.
Flow of Control Java Programming Mrs. C. Furman January 5, 2009.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Selection (if-then-else) Programming Has 3 Types of Control: Sequential (normal): Control of Execution Proceeds One after the Other Selection (if-then-else):
Programming in Java (COP 2250) Lecture 11 Chengyong Yang Fall, 2005.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
Chapter 5 Loops.
Week 4 - Monday.  What did we talk about last time?  Wrapper classes  if statements.
Flow of Control Part 1: Selection
Making Decisions Chapter 5.  Thus far we have created classes and performed basic mathematical operations  Consider our ComputeArea.java program to.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
Chapter 4 Introduction to Control Statements Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else Statements Section 4.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Decision Making Selection structures (if....else and switch/case)
Copyright © 2012 Pearson Education, Inc. Chapter 6 More Conditionals and Loops Java Software Solutions Foundations of Program Design Seventh Edition John.
6/3/2016 CSI Chapter 02 1 Introduction of Flow of Control There are times when you need to vary the way your program executes based on given input.
Copyright © 2012 Pearson Education, Inc. Lab 8: IF statement …. Conditionals and Loops.
Logic Our programs will have to make decisions in terms of what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if.
1 Chapter 3 Selections. 2 Outline 1. Flow of Control 2. Conditional Statements 3. The if Statement 4. The if-else Statement 5. The Conditional operator.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CMP-MX21: Lecture 4 Selections Steve Hordley. Overview 1. The if-else selection in JAVA 2. More useful JAVA operators 4. Other selection constructs in.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Logic Our programs will have to make decisions on what to do next –we refer to the decision making aspect as logic Logic goes beyond simple if and if-else.
CSC1030 HANDS-ON INTRODUCTION TO JAVA Introductory Lab.
5-1 Chapter 5: Conditionals and Loops Topics: –Boolean expressions –Conditional statements –Increment and Decrement Operators (Chapter 2.4) –Repetition.
CSC 1051 M.A. Papalaskari, Villanova University Algorithms Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Decision Statements, Short- Circuit Evaluation, Errors.
Decision Making and Branching
1 Control Structures (Chapter 3) 3 constructs are essential building blocks for programs Sequences  compound statement Decisions  if, switch, conditional.
Control Statements: Part1  if, if…else, switch 1.
1 Flow of Control Chapter 5. 2 Objectives You will be able to: Use the Java "if" statement to control flow of control within your program.  Use the Java.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Decisions and Iterations.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Copyright © 2014 Pearson Addison-Wesley. All rights reserved. 4 Simple Flow of Control.
CompSci 230 S Programming Techniques
Chapter 6 More Conditionals and Loops
Boolean Expressions and If
The order in which statements are executed is called the flow of control. Most of the time, a running program starts at the first programming statement,
Decisions, Decisions, Decisions
SELECTION STATEMENTS (1)
Control Statement Examples
MSIS 655 Advanced Business Applications Programming
Outline Boolean Expressions The if Statement Comparing Data
Topic 1: Problem Solving
Java Programming Control Structures Part 1
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
CSC 1051 – Data Structures and Algorithms I
Conditionals and Loops
Repetition CSC 1051 – Data Structures and Algorithms I Course website:
Presentation transcript:

Decisions, Decisions, Decisions Conditional Statements In Java

Conditional Statements in Java How would you explain to the Java compiler how to do the absolute value function? How would you explain to the Java compiler how to do the absolute value function? Seems simple enough in math Seems simple enough in math All programming languages have some form of decision structure based on logic. All programming languages have some form of decision structure based on logic. The absolute value logic is: The absolute value logic is: If the value is negative, multiply it by -1 If 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 ) { value = -1 * value; }

The if statement The syntax for an if statement in Java is: The syntax for an if statement in Java is: if( condition ) { programming statements… } If the condition is true, java begins executing the code in the {}. Otherwise, the code in the {} is skipped If the condition is true, java begins executing the code in the {}. Otherwise, the code in the {} is skipped Note the style!!! Note the style!!! Indent Braces line up

Conditional Operators Symbol in JavaMeaning ==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)

What will the code print? int testValue = 5; if( testValue > 1 ) { System.out.println( “The testValue is > 1” ); } System.out.println( “End of Program” ); The condition, testValue > 1 is true The condition, testValue > 1 is true Code in the {} will be executed Code in the {} will be executed This code prints: This code prints: The testValue is >1 End of Program

What will the code print? int testValue = 5; if( testValue < 5 ) { System.out.println( “The testValue is < 5” ); } System.out.println( “End of Program” ); The condition, testValue > 1 is false The condition, testValue > 1 is false Code in the {} will be skipped Code in the {} will be skipped This code prints: This code prints: End of Program

What is the output?

Exercises 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 IfTest1 { public static void main( String[] args ) { System.out.println( “Enter a your age” ); Scanner input = new Scanner( System.in ); int age = input.nextInt(); final int LISCENCE_AGE = 16; if( age >= LISCENCE_AGE ) { System.out.println( “You are old enough to get your driver’s license” ); } 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 is greater than or equal to 18 Alter the code to print “You are old enough to vote” if the age is greater than or equal to 18 Alter the code to print “You may pay the child rate” if the age is less than 13 Alter the code to print “You may pay the child rate” if the age is less than 13

if … else statements Another programming feature with decisions is the if… else statement Another programming feature with decisions is the if… else statement Suppose you’re charging admission for a theatre and the ticket prices are for children or adults. Suppose you’re charging admission for a theatre and the ticket prices are for children or adults. Adult: age >= 18 Adult: age >= 18 Child: not an adult Child: 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, otherwise charge child price If age is 18 or higher, charge adult price, otherwise charge child price The new keyword in our problem is otherwise which translates in Java to else The new keyword in our problem is otherwise which translates in Java to else

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 CHILD_PRICE = 8.25; int ticketPrice; if( age >= 18 )//this person is an adult { ticketPrice = ADULT_PRICE; } else//this person is not an adult, therefore a child { ticketPrice = CHILD_PRICE; ticketPrice = CHILD_PRICE;} System.out.println( “Your ticket price is: “ + ticketPrice ); if … else statements

The syntax for if … else in java is: The syntax for if … else in java is: if( condition ) { programming statements if true }else{ programming statements if false } If the original condition is true, then the code in the {} associated with the if statement is executed If the original condition is true, then the code in the {} associated with the if statement is executed Otherwise, the code is ignored and the code in the {} associated with the else statement is executed Otherwise, the code is ignored and the code in the {} associated with the else statement is executed if … else

What Will the Code Print? public class IfElseTest { public static void main( String[] args ) { int hoursPastMidNight = 11; if( hoursPastMidNight <= 12 )//entered a negative! { System.out.println( “It is ” + hoursPastMidNight + “am” ); }else{ 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” ); }} The first statement is true The first statement is true The code in the {} attached to the if is executed The code in the {} attached to the if is executed The code in the {} attached to the else is ignored The code in the {} attached to the else is ignored The result is: The result is: It is 11am End of Program

What Will the Code Print? public class IfElseTest { public static void main( String[] args ) { int hoursPastMidNight = 21; if( hoursPastMidNight <= 12 )//entered a negative! { System.out.println( “It is ” + hoursPastMidNight + “am” ); }else{ hoursPastMidNight -= 12;//convert to 12 hour time System.out.println( “It is ” + hoursPastMidNight + “pm” ); } System.out.println( “End of program” ); }} The first statement is false The first statement is false The code in the {} attached to the if is ignored The code in the {} attached to the if is ignored The code in the {} attached to the else is executed The code in the {} attached to the else is executed The result is: The result is: It is 9pm End of Program

What is the output?

Example Copy and paste the program into a new project Copy and paste the program into a new project public class IfElseTest { public static void main( String[] args ) { System.out.print( “Please enter a positive integer: “ ); Scanner input = new Scanner( System.in ); int userInput = input.nextInt(); if( userInput < 0 )//entered a negative! { System.out.println( “I said a POSITIVE!” ); System.out.println( “What’s the matter with you!” ); }else{ System.out.println( “Thank you for following the instructions” ); } System.out.println( “End of program” ); }} Compile and run the program Compile and run the program 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 years 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 years Alter the code to check how many times a person has been late to class this year. Give them a mean message if it’s more than 5 times! Alter the code to check how many times a person has been late to class this year. Give them a mean message if it’s more than 5 times!

Block 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 statement: A condition or loop with only one statement in the body does not require a block statement: Ex. Ex. if( age > 16 ) { System.out.println( “You may get your liscence” ); } Ex. Ex. if( age > 16 ) 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 errors You can omit the block statements if you wish, but it is likely to result in more errors

Block 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 to If we add braces it is clearer which it belongs to

Fixing Errors

Tracing by hand

And finally, if…else if…else What about when there are several conditions that are related? What about when there are several conditions that are related? In order to ensure that only one statement is executed, we need to chain the if’s together. In order to ensure that only one statement is executed, we need to chain the if’s together. The next two slides show an example where the limitations of only having if are illustrated The next two slides show an example where the limitations of only having if are illustrated

A Whole Bunch of if’s if( richterScale < 1 ) { System.out.println( “Didn’t even feel it” ); } if( richterScale < 4 ) { System.out.println( “All my dishes broke :(” ); } if( richterScale < 7 ) { System.out.println( “Whole lotta shakin going on!” ); } if( richterScale < 10 ) { 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! What does the code print if richterScale = 5? What does the code print if richterScale = 5? Whole lotta shakin going on! Run for the hills! True False True

Fixing the previous example if( richterScale < 1 ) { System.out.println( “Didn’t even feel it” ); } else if( richterScale < 4 ) { System.out.println( “All my dishes broke :(” ); } else if( richterScale < 7 ) { System.out.println( “Whole lotta shakin going on!” ); }else{ 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! What does the code print if richterScale = 5? What does the code print if richterScale = 5? Whole lotta shakin going on! True, ignore anything else in the group False No if’s were true, so automatically go here

if...else if…else Java evaluates EVERY if statement. Java evaluates EVERY if statement. The only exception is when they are joined by the reserved word else The only exception is when they are joined by the reserved word else Java evaluates a sequence of if/else if/else statements until the FIRST one is true. Java evaluates a sequence of if/else if/else statements until the FIRST one is true. If none are true then the else is evaluated If none are true then the else is evaluated Only one set of statements in the group will be evaluated Only one set of statements in the group will be evaluated

if...else if…else syntax if( condition ) { statements if true } else if( condition ) { statements if true }…… else if( condition ) { statements if true }else{ statements if all others in the group were false }

What is Printed? int age = 21; if( age <= 12 )//12 or younger { System.out.println( "Your cost is $5.50" ); } else if( age <=19 ) //older than 12 but 19 or younger { System.out.println( "Your cost is $8.25" ); } else if( age <= 64 ) //older than 19 but 64 or younger { System.out.println( "Your cost is $13.75" ); } else //older than 64 { System.out.println( "Your cost is $5.50" ); } Your cost is $13.75 Your cost is $13.75 False True, everything else below ignored