Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Similar documents
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 2016 Howard Rosenthal

Control Statements Review CSC 123 Fall 2018 Howard Rosenthal

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Repetition CSC 121 Fall 2014 Howard Rosenthal

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Topics. Chapter 5. Equality Operators

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Flow Control. CSC215 Lecture

Flow of Control. Flow of control The order in which statements are executed. Transfer of control

V2 2/4/ Ch Programming in C. Flow of Control. Flow of Control. Flow of control The order in which statements are executed

In Java, data type boolean is used to represent Boolean data. Each boolean constant or variable can contain one of two values: true or false.

Chapter 4: Making Decisions

Chapter 4: Making Decisions

Chapter 3. Selections

Chapter 4: Making Decisions. Copyright 2012 Pearson Education, Inc. Sunday, September 7, 14

Control Structures in Java if-else and switch

St. Edmund Preparatory High School Brooklyn, NY

Motivating Examples (1.1) Selections. Motivating Examples (1.2) Learning Outcomes. EECS1022: Programming for Mobile Computing Winter 2018

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

Chapter 4: Control Structures I

LECTURE 04 MAKING DECISIONS

Introduction to Computer Science Unit 2. Notes

2.8. Decision Making: Equality and Relational Operators

Selections. EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG

Loops. CSE 114, Computer Science 1 Stony Brook University

STUDENT LESSON A12 Iterations

REPETITION CONTROL STRUCTURE LOGO

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Conditional Programming

Decision Making in C

Introduction to Java & Fundamental Data Types

Algorithms and Conditionals

CMPT 125: Lecture 4 Conditionals and Loops

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

Programming with Java

Module 3 SELECTION STRUCTURES 2/15/19 CSE 1321 MODULE 3 1

Methods CSC 121 Fall 2016 Howard Rosenthal

4.1. Chapter 4: Simple Program Scheme. Simple Program Scheme. Relational Operators. So far our programs follow a simple scheme

Chapter 3: Operators, Expressions and Type Conversion

Lesson 7 Part 2 Flags

Flow of Control. Chapter 3

Repetition Structures

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

Methods CSC 121 Spring 2017 Howard Rosenthal

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Conditionals and Loops

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Flow of Control: Loops. Chapter 4

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Logical Operators and if/else statement. If Statement. If/Else (4.3)

5. Selection: If and Switch Controls

Chapter 3 Selection Statements

COMP 202 Java in one week

Selections. CSE 114, Computer Science 1 Stony Brook University

Full file at

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Controls Structure for Repetition

Please answer the following questions. Do not re-code the enclosed codes if you have already completed them.

Control Structures in Java if-else and switch

Flow of Control. Chapter 3

Problem Solving With Loops

Repetition, Looping. While Loop

Darrell Bethea May 25, 2011

CS1150 Principles of Computer Science Loops (Part II)

Oct Decision Structures cont d

Introduction. C provides two styles of flow control:

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

L o o p s. for(initializing expression; control expression; step expression) { one or more statements }

Logic & program control part 2: Simple selection structures

Conditional Statement

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

COMP-202: Foundations of Programming. Lecture 3: Boolean, Mathematical Expressions, and Flow Control Sandeep Manjanna, Summer 2015

CSE 20. SAMPLE FINAL Version A Time: 180 minutes. The following precedence table is provided for your use:

AP CS Unit 3: Control Structures Notes

Pace University. Fundamental Concepts of CS121 1

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Computer Programming, I. Laboratory Manual. Experiment #3. Selections

Building Java Programs

Variables and data types

Slide 1 CS 170 Java Programming 1 The Switch Duration: 00:00:46 Advance mode: Auto

Example: Monte Carlo Simulation 1

STUDENT LESSON A7 Simple I/O

Some Sample AP Computer Science A Questions - Solutions

Course Outline. Introduction to java

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

There are algorithms, however, that need to execute statements in some other kind of ordering depending on certain conditions.

CS 106 Introduction to Computer Science I

CSEN 202 Introduction to Computer Programming

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Following is the general form of a typical decision making structure found in most of the programming languages:

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

Lecture 5 Tao Wang 1

Chapter 4: Conditionals and Recursion

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Introduction to Computer Science Unit 2. Notes

Transcription:

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 2016 Howard Rosenthal

Lesson Goals Understand Control Structures Understand how to control the flow of a program via selection mechanisms Understand if, if-else and switch statements Build programs with nested layers of decision making Building blocks of execution code Understand how to deal with the dangling else Understand else-if and how it is different from switch Understand the conditional operator 2

Control Structures in Java There are three control structures in Java Sequence Structure Built into Java Ensures that statements execute one after the other in the order they are written, unless directed otherwise Selection Structure (Chapter 4) Based on truth or falsity In Java includes the if, if else, if... else if, and switch statements Repetition Structure (Chapter 5) Allows for repetition of the same group of statements multiple times, as long as a condition is met In Java includes the do, do while, for, and enhanced for statements Also known as iteration statements or looping statements 3

Two Way Decisions Windshield wipers are controlled with an ON-OFF switch. The flowchart at right shows how this decision is made. Start at the top of the chart then follow the line to the question: is it raining? The answer is either true or false. If the answer is true, follow the line labeled True, perform the instructions in the box "wipers on", follow the line to "continue". If the answer is false, follow the line labeled False, perform the instructions in the box "wipers off", follow the line to "continue". The windshield wiper decision is a two-way decision (sometimes called a binary decision). The decision seems small, but in programming, complicated decisions are made by executing many small decisions. 4

The Basic Syntax of the if Statement if (boolean expression) statement 1; statement 2; o 0 o statement n; The statements inside the block (delineated by a pair of braces) are executed only if the boolean statement is true You should use the braces even if there is only a single statement inside the block even though this isn t required No semicolon on the if statement An if with a single statement following it does not require curly braces, however, it us best to use them all the time at first if (boolean expression) statement 1; 5

Basic Terminology An if statement is also called a conditional or selection statement The phrase if (boolean expression) is called the if clause The boolean expression itself is called the condition The statements inside the curly braces comprise a block You can nest if statements inside each other 6

A Very Simple Example public class SimpleIfStatementDemo1 public static void main(string args[]) //Declaring a variable "test" and initializing it with a value 10 int test = 10; //Checking if "test" is greater than 5 if (test > 5) //This block will be executed only if "test" is greater than 5 System.out.println("Success"); //The if block ends. System.out.println("Executed successfully"); 7

The Basic Syntax of the if-else Statement Similar to the if statement, but exclusively executes an alternative set of statement(s) if the conditional is false if (boolean expression) // always evaluates to either true or false statement 1; statement 2; o 0 o statement n; else statement a; statement b; o 0 o statement x; Note: Once again if there is only a single statement then braces are not required if (boolean expression) // always evaluates to either true or false statement 1; else statement a; 8

A Simple Example of if-else import java.util.scanner; class NumberTester public static void main (String[] args) Scanner keyboard = new Scanner( System.in ); int num; System.out.println("Enter an integer:"); num = keyboard.nextint(); if ( num < 0 ) System.out.println("The number " + num + " is negative"); num = num +5; else System.out.println("The number " + num + " is zero or positive"); num = num -4; System.out.println("The number is now " + num ); System.out.println("Good-bye for now"); 9

if else if Syntax Allows for testing for multiple different conditions Only the first case that tests as true will be executed If there is no else statement at the end there may not be execution of any of the blocks if (boolean expression) // always evaluates to either true or false statement 1; statement 2; o 0 statement n; else if(boolean expression) // always evaluates to true or false statement a; statement b; o 0 statement x; else //optional statement a; statement b; o 0 statement x; 10

An else if Example //This program assigns a letter grade based on a character grade import java.util.scanner; class IfElseDemo public static void main(string[] args) Scanner keyboard = new Scanner(System.in); System.out.println("Enter the grade"); int testscore = keyboard.nextint(); char grade; if (testscore >= 90) grade = 'A'; else if (testscore >= 80) grade = 'B'; else if (testscore >= 70) grade = 'C'; else if (testscore >= 60) grade = 'D'; else grade = 'F'; System.out.println("Grade = " + grade); Note: If you reverse the order then you would need to compare from bottom to top using <= Be careful in use of > vs. >=, etc. 11

A Note On boolean Expressions Be careful when using float or double type variables in boolean expressions Since there is always limited precision the possibility of an execution error exists, especially after more complex mathematical operations Example: (7.13*2.9)/(3.6*2.95) may be different than (7.13/(3.6*2.95))*2.9 See DecimalCompare.java 12

The Dangling if (1) Rule - An else matches with the nearest, previous, unmatched if that's not in a block. if ( num > 0 ) if ( num < 10 ) // Previous unmatched if System.out.println( "aaa" ) ; else // Matches with previous unmatched if System.out.println( "bbb" ) ; In the example above, the else is indented with the inner if statement. It prints "bbb" only if num > 0 and num >= 10, which means it prints only if num is 10 or greater. In the example below, the else is indented with the outer if statement. if ( num > 0 ) if ( num < 10 ) // Previous unmatched if System.out.println( "aaa" ) ; else // Matches with previous unmatched if System.out.println( "bbb" ) ; Which one does else match with? It picks the closest if unless there is a further clarification with the use of braces. This phenomenon of having to pick between one of two possible if statements is called the dangling else. Depending on which if the else is paired with, you can get different results. By now, you should know that Java doesn't pay attention to indentation. So both examples above are the same to Java, which means that it makes its determination based strictly on the syntax. To the Java Compiler there is no ambiguity (You can t say That s not what I really meant ) The compiler doesn t care about indenting. But you should for clarity 13

The Dangling if (2) What if we wanted the else to match with the first if? Then, we need braces. if ( num > 0 ) // Previous unmatched if if ( num < 10 ) // Unmatched, but in block System.out.println( "aaa" ) ; else // Matches with previous unmatched if not in block System.out.println( "bbb" ) ; //This prints if num <= 0. The else above matches with the previous, unmatched if not in a block. This happens to be the outer if. There is an unmatched if that's the inner if, but that's in a block, so you can't match to it. Notice the else sits outside of the block. An else can not match to a previous if if the else is outside the block, where the closest if is found. 14

The Dangling if The Rules Summarized Every else must match with a unique if. You can't have two or more else matching to the same if. If there is no matching if for an else, then your program won't compile. Each else must be preceded by a valid if Fortunately, your program fails to compile if you don't do this. Use Braces If you always use a block for if body and else body, then you can avoid confusion. However, it's useful to know the correct rules. 15

The switch Statement The syntax of a switch statement looks like: switch ( expr ) case literal1: case literal1 body case literal2: case literal2 body case literal3: case literal3 body default: default body Unlike if statements which contain a condition in the parentheses, switch contains an expression. This expression must be type int, char or String. (Note: String is a newer feature, and the book says only int or char) The semantics of switch are: Evaluate the expression Begin looking at each case, starting top to bottom If the value of the expression matches the case, then run the body Note: The case keyword has to be followed by a literal or a constant expression. It can't be a range or something that tests If you run a break statement, you then exit the switch If you don't run a break statement, and you are at the end of a body, run the next body. Keep running bodies until you exit If no match is made to the cases, run the default, if it exists. The default case is always run last, no matter where it appears. (It should be placed last, though). It is not mandatory to have a default statement. 16

Examples of the Switch Statement int x = 4 ; switch ( x ) case 2: System.out.println( "TWO" ) ; break ; case 4: System.out.println( "FOUR" ) ; break ; case 6: System.out.println( "SIX" ) ; break ; default: System.out.println( "DEFAULT" ) ; This evaluates x to 4. It skips case 2 since the value 4 doesn't match 2. It does match case 4. It runs the body and prints FOUR". Then it runs break and exits the switch. 17

Examples of the Switch Statement (2) Most of the times, you will end each case with break. Both C and languages like Java force you to write a statement that should be there all the time. Let's see what happens when you leave it out. int x = 4 ; switch ( x ) case 2: System.out.println( "TWO" ) ; case 4: System.out.println( "FOUR" ) ; case 6: System.out.println( "SIX" ) ; default: System.out.println( "DEFAULT" ) ; This prints out: FOUR SIX DEFAULT That's probably not what the user had in mind. Without the break, each time a body runs, it falls through and starts running the next body, and the next, after it matches the correct case. However, there are cases where you will want to execute multiple statements from multiple cases (see next example) 18

Examples of the Switch Statement (3) You can combine cases together. int x = 4 ; switch ( x ) case 1: case 3: case 5: System.out.println( "ODD" ) ; break ; case 2: case 4: case 6: System.out.println( "EVEN" ) ; break ; default: System.out.println( "DEFAULT" ) ; 19

A Few Addi%onal Notes On the switch Statement Every switch statement can be implemented as an if/if else type statement It doesn t always work the other way around Obviously if the if/else is doing more complex comparisons (i.e. >=) or using floating point numbers, then this can t be implemented in a switch statement 20

The Condi%onal Operator (1) The conditional operator is used like this: true-or-false-condition? value-if-true : value-if-false Here is how it works: The true-or-false-condition evaluates to true or false. That value selects one choice: If the true-or-false-condition is true, then evaluate the expression between? and : If the true-or-false-condition is false, then evaluate the expression between : and the end. The result of evaluation is the value of the entire conditional expression. This approach can be used in assignment statements 21

The Condi%onal Operator (2) int a = 7, b = 21; System.out.println( "The min is: " + (a < b? a : b ) ); The output would be: The min is 7 22

The Condi%onal Operator (3) double value = -34.569; double absvalue; absvalue = (value < 0 )? -value : value ; ------------- ------ The constant value +34.569 is assigned to absvalue 23

An Example Using String Features That Will Be Taught Later import java.util.scanner; class RainTester public static void main (String[] args) Scanner keyboard = new Scanner( System.in ); String answer; System.out.print("Is it raining? (Y or N): "); answer = keyboard.nextline(); if ( answer.equals("y") ) // is answer exactly "Y"? System.out.println("Wipers On"); // true branch else System.out.println("Wipers Off"); // false branch 24

Now That Your Programs Are GeWng More Complex Always check your programs through each of the else cases, switch gates etc. To do this you need to develop a set of test cases A test case has components that describe an input, action or event and an expected response, to determine if a feature of an application is working correctly Your test cases must be expansive enough to cover the full range of possibilities For instance if there is a statement if (x>4) you don t need to test for every possibility greater than 4, but you need to test for at least one. Typically we build a software test verification matrix 25

Sample Test Matrix Y 2 3 4 X 1 R1 R2 R3 2 R4 R5 R6 5 R7 R8 R9 7 R10 R11 R12 Test for all possible combinations When there are multiple variables break the testing into smaller pieces Always test for different and outlying conditions Positive, zero and negative numbers First and last number and some element in the middle when processing a list 26

Special Topic - Rounding Java includes different methods and techniques for rounding, some of which we will learn later this year However, if you are interested in rounding do the following: 1. Take the floating point number and multiply by 1000; Cast the number multiplied by 1000 as an int (if it is not too large for an int, otherwise use long 2. Take the original floating point number and multiply by 100; Cast the number multiplied by 100 as an int (if it is not too large for an int, otherwise use long 3. Determine if the last digit of the int value multiplied by 1000 is greater than or equal to 5 4. If the last digit is greater than or equal to 5 divide by 100.0 and add 1, otherwise divide by 100 Example: double x = 123.45678, xround; int xintthous = (int)(x*1000);// this is 123456 int xinthund = (int)(x*100);// this is 12345 if (xintthous%10 >=5) xround = (xinthund+1)/100.; else xround = (xinthund/100.); See full program in RoundingExample.java 27

Programming Exercises Class (1) Exercise 1. Sort Three Write a program that accepts three integers and displays the number in order from lowest to highest. 28

Programming Exercises Class (2) Exercise 8. Toll Free Numbers As of the year 2008, a 10 digit number that begins with 800, 888, 877, or 866 has been toll free. Write a program that reads in a 10 digit phone number and displays a message that states whether the number is toll free or not. 29

Programming Exercises Lab (1) Exercise 3. Positive Sum Write a program that prompts for five integers and calculates the sum of those that are positive. 30

Programming Exercises Lab (2) Exercise11. Grade Conversion A certain school assigns number grades ranging from 0-100. Write a program that queries the user for a numerical score and converts the score to a letter grade according to thee following criteria: 0-59:F; 60-69 D: 70-72, C-: 73-76, C: 77-79 C+; 80-82: B-; 83-86: B; 87-89: B+; 90-92: A-; 93-96: A; 97-100 A+ 31