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

Similar documents
Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Fall 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

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.

Flow Control. CSC215 Lecture

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

Topics. Chapter 5. Equality Operators

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

Chapter 3. Selections

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

2.8. Decision Making: Equality and Relational Operators

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

STUDENT LESSON A12 Iterations

Loops. CSE 114, Computer Science 1 Stony Brook University

Chapter 4: Control Structures I

Control Structures in Java if-else and switch

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

Lesson 7 Part 2 Flags

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

Introduction to Computer Science Unit 2. Notes

REPETITION CONTROL STRUCTURE LOGO

Chapter 4: Making Decisions

Chapter 4: Making Decisions

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

St. Edmund Preparatory High School Brooklyn, NY

Conditional Programming

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

Repetition, Looping. While Loop

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

CS1150 Principles of Computer Science Loops (Part II)

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

DECISION STRUCTURES: USING IF STATEMENTS IN JAVA

LECTURE 04 MAKING DECISIONS

Algorithms and Conditionals

CMPT 125: Lecture 4 Conditionals and Loops

Introduction to Java & Fundamental Data Types

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

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

Methods CSC 121 Fall 2016 Howard Rosenthal

Flow of Control: Loops. Chapter 4

Controls Structure for Repetition

! 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

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

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

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

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

Decision Making in C

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

COMP 202 Java in one week

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

Repetition Structures

Darrell Bethea May 25, 2011

Problem Solving With Loops

Methods CSC 121 Spring 2017 Howard Rosenthal

Chapter 4: Conditionals and Recursion

AP CS Unit 3: Control Structures Notes

All about flow control

Conditionals and Loops

Chapter 3 Selection Statements

Selections. CSE 114, Computer Science 1 Stony Brook University

3chapter C ONTROL S TATEMENTS. Objectives

Handout 4 Conditionals. Boolean Expressions.

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

Control Flow Statements

Flow of Control. Chapter 3

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

CONDITIONAL EXECUTION

Programming with Java

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

Flow of Control. Chapter 3

Oct Decision Structures cont d

Arrays and Lists CSC 121 Fall 2014 Howard Rosenthal

Java Programming: Guided Learning with Early Objects Chapter 5 Control Structures II: Repetition

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

Course Outline. Introduction to java

Midterm Examination (MTA)

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

COMP 202 Java in one week

5. Selection: If and Switch Controls

Control Structures in Java if-else and switch

CS 106 Introduction to Computer Science I

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

Logic & program control part 2: Simple selection structures

Example: Monte Carlo Simulation 1

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

Introduction to Java Applications

Loops. GEEN163 Introduction to Computer Programming

CSE 114 Computer Science I

Check out how to use the random number generator (introduced in section 4.11 of the text) to get a number between 1 and 6 to create the simulation.

ECE 122. Engineering Problem Solving with Java

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

Lecture 5 Tao Wang 1

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

Building Java Programs

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

Over and Over Again GEEN163

Arrays and Lists CSC 121 Fall 2016 Howard Rosenthal

Transcription:

Selec%on and Decision Structures in Java: If Statements and Switch Statements CSC 121 Spring 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 Understand the conditional operator 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 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, 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 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 Simple_If_Statement_Demo1 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; 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 is now " + num ); num = num -4; System.out.println("The number " + num + " is zero or positive"); System.out.println("Good-bye for now"); 9

if else if Syntax 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 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 If_Else_Demo 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); 11

The Dangling if 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 it pick? It picks the first one. 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 12

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 a block, while the previous if is inside. 13

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 match, 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. 14

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. 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. 15

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. 16

Examples of the Switch Statement (2) Most of the times, you must 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. 17

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" ) ; 18

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 19

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 20

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

An Example Using String Features That Will Be Taught Later import java.util.scanner; class Rain_Tester 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 22

Now That Your Programs Are GeUng 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 23

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 24

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. 25

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. 26

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. 27

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+ 28