Week 4: Conditional Execution 1.  So far we have only considered Java programs that do one thing after another, in sequence  Our programs have not had.

Slides:



Advertisements
Similar presentations
Week 7: Input and Output 1.  Now we are going to talk a little bit about output  You have a lot of experience with System.out.println() and System.out.print()
Advertisements

CSE 1301 Lecture 5B Conditionals & Boolean Expressions Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 10, 2009.
CS0007: Introduction to Computer Programming
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
CS 106 Introduction to Computer Science I 09 / 25 / 2006 Instructor: Michael Eckmann.
Week 2: Primitive Data Types 1.  Programming in Java  Everything goes inside a class  The main() method is the starting point for executing instructions.
5-1 Flow of Control Recitation-01/25/2008  CS 180  Department of Computer Science  Purdue University.
1 CS 177 Week 4 Recitation Slides Conditionals. 2 Announcements Project 1 is due on Feb. 7th 9pm (extended) Project 2 will be posted today (Feb. 5th)
Selection Statements choice of one among several blocks of code Java supports 3 kinds of selection statements: if statement – selects one block or leaves.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Logical Operators and Conditional statements
Chapter 4 Making Decisions
C++ for Engineers and Scientists Third Edition
COMP 110 Introduction to Programming Mr. Joshua Stough September 19, 2007.
CS 106 Introduction to Computer Science I 09 / 28 / 2007 Instructor: Michael Eckmann.
CSM-Java Programming-I Spring,2005 Control Flow Lesson - 3.
The switch Statement, DecimalFormat, and Introduction to Looping
CONTROL STATEMENTS IF-ELSE, SWITCH- CASE Introduction to Computer Science I - COMP 1005, 1405 Instructor : Behnam Hajian
Week 5 - Wednesday.  What did we talk about last time?  Exam 1!  And before that?  Review!  And before that?  if and switch statements.
1 Chapter 4: Selection Structures. In this chapter, you will learn about: – Selection criteria – The if-else statement – Nested if statements – The switch.
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
1 Lecture 5: Selection Structures. Outline 2  Control Structures  Conditions  Relational Operators  Logical Operators  if statements  Two-Alternatives.
Week 4 - Wednesday.  What did we talk about last time?  if statements  else statements  Nested selection statements.
5-1 Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements,
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.
Pseudocode When designing an ALGORITHM to solve a problem, Pseudocode, can be used. –Artificial, informal language used to develop algorithms –Similar.
Chapter 4 Introduction to Control Statements Section 1 - Additional Java Operators Section 2 - If Statements Section 3 - If-Else Statements Section 4.
CPS120: Introduction to Computer Science Decision Making in Programs.
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.
Making Decisions (True or False) Relational Operators >greater than =greater than or equal to
© The McGraw-Hill Companies, 2006 Chapter 2 Selection.
©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.
Week 3 - Wednesday.  What did we talk about last time?  Other C features  sizeof, const  ASCII table  printf() format strings  Bitwise operations.
Selection Statements. Introduction Today we learn more about learn to make decisions in Turing ▫Nested if statements, ▫case statements.
CS 106 Introduction to Computer Science I 09 / 26 / 2007 Instructor: Michael Eckmann.
Java Programming Fifth Edition Chapter 5 Making Decisions.
Chapter 5: Making Decisions. Objectives Plan decision-making logic Make decisions with the if and if…else structures Use multiple statements in if and.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
CS 0401 Debugging Hints and Programming Quirks for Java by John C. Ramirez University of Pittsburgh.
What is a Boolean expression?
Decision Statements, Short- Circuit Evaluation, Errors.
Programming Language C++ Lecture 3. Control Structures  C++ provides control structures that serve to specify what has to be done to perform our program.
Chapter 2: Fundamental Programming Structures in Java Adapted from MIT AITI Slides Control Structures.
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.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Week 3 - Friday.  What did we talk about last time?  Preprocessor directives  Other C features  sizeof, const  ASCII table  printf() format strings.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
C++ for Engineers and Scientists Second Edition Chapter 4 Selection Structures.
The if…else Selection Statement
CS0007: Introduction to Computer Programming
COMP 14 Introduction to Programming
Week 3 - Friday CS222.
Selections Java.
The switch Statement, and Introduction to Looping
Week 4 - Wednesday CS 121.
CHAPTER 4 Selection CSEG1003 Introduction to Computing
Lecture 3- Decision Structures
Week 4 - Monday CS 121.
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,
CS 177 Week 4 Recitation Slides
Conditions and Ifs BIS1523 – Lecture 8.
The System.exit() Method
Module 3 Selection Structures 6/25/2019 CSE 1321 Module 3.
Presentation transcript:

Week 4: Conditional Execution 1

 So far we have only considered Java programs that do one thing after another, in sequence  Our programs have not had the ability to choose between different possibilities  Now, they will! 2

 The if -statement:  “x is small” will only print if x is less than 5  In this case, we know that it is, but x could come from user input or a file or elsewhere int x = 4; if( x < 5 ) System.out.println(“x is small!”); 3

The if part Any boolean expression Any single executable statement if( condition ) statement; 4

 Any expression that evaluates to a boolean is legal in an if -statement  Examples:  x == y  mass >  Character.isDigit(gender)  s.equals(“help”) && (z < 4) 5

 The most common condition you will find is a comparison between two things  In Java, that comparison can be:  == equals  != does not equal  < less than  <= less than or equal to  > greater than  >= greater than or equal to 6

 You can use the == operator to compare any two things of the same type  Different numerical types can be compared as well ( 3 == 3.0 )  Be careful with double types, is not equal to int x = 3; if( x == 4 ) System.out.println(“This doesn’t print”); 7

 Any place you could have used the == operator, you can use the != operator  If == gives true, the != operator will always give false, and vice versa  If you want to negate a condition, you can always use the ! as a not is the same as if( x != 4 ) if( !(x == 4) ) 8

 Remember, a single equal sign ( = ) is the assignment operator (think of a left-pointing arrow)  A double equals ( == ) is a comparison operator if( y = 6 ) //compiler error! if( y == 6 ) //how to test if y is 6! 9

 Inequality is very important in programming  You may want to take an action as long as a value is below a certain threshold  For example, you might want to keep bidding at an auction until the price is greater than what you can afford if( x <= 4 ) if( x < 4 ) // what is the difference? 10

 Just like less than or equal to, except the opposite  Note that the opposite of and the opposite of >= is <  Thus,  !( x y )  !( x >= y ) is equivalent to ( x < y ) 11

 Sometimes you have to make a decision  If a condition is true, you go one way, if not, you go the other  For example:  If I pass CS177, ▪ Then I throw a party to celebrate  Otherwise, ▪ I take it again and go to class next time 12

 Notice the nature of this kind of condition  Both outcomes cannot happen  Either a party gets thrown or you take CS 177 again  For these situations, we use the else construct 13

Two different outcomes if( condition ) statement1; else statement2; 14

double balance = …; if( balance < 0 ) System.out.println(“You are in debt!”); else System.out.println(“You have $” + balance); 15

 No problem  Use braces to treat a group of statements like a single statement if( x == 4 ) { System.out.println(“I hate 4”); System.out.println(“Let’s change x.”); x = 10; } 16

if( condition ) { statement1; statement2; … statementn; } A whole bunch of statements 17

 Sometimes you want to make one set of decisions based on another set of decisions  if -statements can be nested inside the bodies of other if -statements  You can put if -statements inside of if - statements inside of if -statements… going arbitrarily deep 18

if( condition1 ) { statement1; if( condition2 ) { if( condition3 ) statement2; … } 19

 For the next example, recall the 4 quadrants of the Cartesian coordinate system x-x y -y (0,0)

 Find which quadrant the point (x,y) is in if( x >= 0.0 ) { if( y >= 0.0 ) System.out.println(“Quadrant 1”); else System.out.println(“Quadrant 4”); } else { if( y >= 0.0 ) System.out.println(“Quadrant 2”); else System.out.println(“Quadrant 3”); } 21

 You can list a sequence of exclusive possibilities using nesting: if( index == 1 ) System.out.println(“First”); else if( index == 2 ) System.out.println(“Second”); else if( index == 3 ) System.out.println(“Third”); else System.out.println(“Oops. Problem”); } 22

 Now you are controlling the flow of execution in your program  There is a wider range of mistakes you can make when giving instructions  Huge chunks of code can be executed or skipped by mistake  Here are a few things to watch out for… 23

 Remember that an if -statement is not an executable statement  It does not end with a semicolon if( balance < 0 ); // empty statement { // this block always runs System.out.println(“You owe a fee!”); balance -= 15; } 24

 In some languages, indentation actually matters  Java ignores whitespace  “Negotiate!” prints no matter what if( enemies > 2 ) System.out.println(“Run away!”); else defense = true; System.out.println(“Negotiate!”); 25

 It’s easy to make logical errors when writing conditions  If an airline allows two or fewer bags on the plane, someone might code that as:  But this is too restrictive. It should be: if( bags < 2 ) // only allows 1 or 0 boarding = true; if( bags <= 2 ) boarding = true; 26

 Sometimes it’s easy to get a condition backwards  Try not to assume you wrote the condition correctly  Always test your code if( number % 3 == 0 ) System.out.println(“Not divisible by 3!”); else System.out.println(“Divisible by 3!”); 27

 Sometimes you probably break the speed limit  But, there’s one speed limit you can never break  The speed of light c is about 3 x 10 8 miles/second  Given a variable named speed of type double, what’s an if - statement that will print an error message if speed is larger than c? 28

 The simplest answer:  What if we want to add a message if the speed is legal? if( speed > 3.0e8 ) System.out.println(“Not so fast!”); if( speed > 3.0e8 ) System.out.println(“Not so fast!”); else System.out.println(“That speed is fine.”); 29

 Assume that you have a variable called base of type char  Let base contain one of: ‘A’, ‘C’, ‘G’, ‘T’  Write a series of if - and else -statements that will print out the chemical name of the base denoted by the corresponding character  A -> Adenine  C -> Cytosine  G -> Guanine  T -> Thymine 30

 What if you want to take care of upper and lower cases? if( base == ‘A’ ) System.out.println(“Adenine”); else if( base == ‘C’ ) System.out.println(“Cytosine”); else if( base == ‘G’ ) System.out.println(“Guanine”); else if( base == ‘T’ ) System.out.println(“Thymine”); else System.out.println(“Base is not correct”); 31

 Is there a simpler way? if( base == ‘A’ || base == ‘a’ ) System.out.println(“Adenine”); else if( base == ‘C’ || base == ‘c’ ) System.out.println(“Cytosine”); else if( base == ‘G’ || base == ‘g’ ) System.out.println(“Guanine”); else if( base == ‘T’ || base == ‘t’ ) System.out.println(“Thymine”); else System.out.println(“Base is not correct”); 32

base = Character.toUpperCase( base ); if( base == ‘A’ ) System.out.println(“Adenine”); else if( base == ‘C’ ) System.out.println(“Cytosine”); else if( base == ‘G’ ) System.out.println(“Guanine”); else if( base == ‘T’ ) System.out.println(“Thymine”); else System.out.println(“Base is not correct”); 33

 But, didn’t that DNA example seem a little clunky?  Surely, there is a cleaner way to express a list of possibilities  Yes! It is the switch statement 34

switch( data ) { case value1: statements 1; case value2: statements 2; … case valuen: statements n; default: default statements; } 35

switch( base ) { case‘A’: System.out.println(“Adenine”); break; case‘C’: System.out.println(“Cytosine”); break; case‘G’: System.out.println(“Guanine”); break; case‘T’: System.out.println(“Thymine”); break; default: System.out.println(“Base is not correct”); break; // unnecessary } 36

int data = 3; switch( data ) { case 3: System.out.println(“Three”); case 4: System.out.println(“Four”); break; case 5: System.out.println(“Five”); } Both “Three” and “Four” are printed The break is optional The default is optional too 37

1. The data that you are performing your switch on must be either an int or a char 2. The value for each case must be a literal 3. Execution will proceed to the case that matches 4. Execution will continue until it hits a break 5. If no case matches, it will go to default 6. If there is no default, it will skip the whole switch block 38

switch( base ) { case‘A’: case‘a’: System.out.println(“Adenine”); break; case‘C’: case‘c’: System.out.println(“Cytosine”); break; case‘G’: case‘g’: System.out.println(“Guanine”); break; case‘T’: case‘t’: System.out.println(“Thymine”); break; default: System.out.println(“ Base is not correct ”); break; // unnecessary } 39

 Using if -statements is usually safer  if -statements are generally clearer and more flexible  switch statements are only for long lists of specific cases  Be careful about inconsistent use of break 40

 Input can be a messy thing  So far, the only input you have used are the arguments passed into the program  Sometimes a program needs to get input several times from a user 41

 To do this, we are going to use the StdIn library, created by the author of the textbook  Read pages 126 – 130 in Sedgewick  Java provides several other ways of doing input  However, StdIn is simpler than most  The only painful thing is that you have to have another class file in the directory with your program to make it work 42

 The location of the StdIn library is: StdIn.java StdIn.java  This is just a regular Java file  Look through it if you are curious  When you compile code that uses StdIn methods, StdIn.java will automatically be compiled, as long as it is in the same directory 43

 The purpose of StdIn is to let you read stuff that the user types in  If the user is running the program from the command line, he or she will enter input there  If the user is running the program from DrJava, he or she will enter input in the Interactions pane 44

DrJava Command Line 45

 For now, we are only going to focus on a few methods in StdIn MethodUse int readInt() Read in the next int double readDouble() Read in the next double boolean readBoolean() Read in the next boolean char readChar() Read in the next char String readString() Read in the next String String readLine() Read in a whole line String readAll() Read in all remaining input 46

System.out.println(“How many sides does your shape have?”); int sides = StdIn.readInt(); if( sides == 3 ) { System.out.println(“Enter the base and the height:”); double base = StdIn.readDouble(); double height = StdIn.readDouble(); System.out.println(“The area of your triangle is “ + (.5 * base * height )); } else if( sides == 4 ) { System.out.println(“Enter the length and the width:”); double length = StdIn.readDouble(); double width = StdIn.readDouble(); System.out.println(“The area of your rectangle is “ + (length * width)); } else System.out.println(“I don’t know what the area “ + “of your shape is.”); 47

 StdIn is pretty smart  It can ignore whitespace when looking for the next int or double  It is not foolproof  If you try to read in an int and the user types “pigs”, your program will crash 48