Selections. CSE 114, Computer Science 1 Stony Brook University

Similar documents
Chapter 3 Selections. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

Motivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool

Chapter 3 Selection Statements

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. and Java. Chapter 2 Primitive Data Types and Operations

Lecture 1 Java SE Programming

CCHAPTER SELECTION STATEMENTS HAPTER 3. Objectives

Chapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type

Selection Statements. Pseudocode

CONDITIONAL EXECUTION

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

Chapter 3. Selections

3chapter C ONTROL S TATEMENTS. Objectives

Chapter 3, Selection. Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved.

Elementary Programming. CSE 114, Computer Science 1 Stony Brook University

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

Python - Week 3. Mohammad Shokoohi-Yekta

Chapter 2 Primitive Data Types and Operations. Objectives

Eng. Mohammed S. Abdualal

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Outline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors

Lesson 7 Part 2 Flags

Chapter 4 Loops. Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved.

CS1150 Principles of Computer Science Boolean, Selection Statements

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

Chapter 4: Control Structures I

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

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

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

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

Tutorial # 4. Q1. Evaluate the logical (Boolean) expression in the following exercise

Primitive Data, Variables, and Expressions; Simple Conditional Execution

In this lab, you will learn more about selection statements. You will get familiar to

Chapter 2. Elementary Programming

Conditional Programming

Topics. Chapter 5. Equality Operators

Prof. Navrati Saxena TA: Rochak Sachan

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

CS 106 Introduction to Computer Science I

JAVA OPERATORS GENERAL

Decision Structures. Selection. Selection options (in Java) Plain if s (3 variations) Each action could be any of: if else (3 variations)

AP Computer Science A

Chapter 2 Primitive Data Types and Operations

CSE331 Winter 2014, Midterm Examination February 12, 2014

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

Decision Structures. Lecture 3 MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz

Chapter 3: Operators, Expressions and Type Conversion

Control Structures in Java if-else and switch

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

Important Java terminology

QUIZ: What value is stored in a after this

Accelerating Information Technology Innovation

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

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

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

CEN 414 Java Programming

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

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

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

In this chapter, you will:

CSE331 Winter 2014, Midterm Examination February 12, 2014

Building Java Programs

CSS 161 Fundamentals of Compu3ng. Flow control (2) October 10, Instructor: Uma Murthy

CS 106 Introduction to Computer Science I

CS 106 Introduction to Computer Science I

bitwise inclusive OR Logical logical AND && logical OR Ternary ternary? : Assignment assignment = += -= *= /= %= &= ^= = <<= >>= >>>=

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

STUDENT LESSON A12 Iterations

COMP Primitive and Class Types. Yi Hong May 14, 2015

Chapter 2 Elementary Programming

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

The Java language has a wide variety of modifiers, including the following:

Term 1 Unit 1 Week 1 Worksheet: Output Solution

Control Structures in Java if-else and switch

IEEE Floating-Point Representation 1

CS 112 Introduction to Programming

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

Introduction to Object-Oriented Programming

Lecture 9. Assignment. Logical Operations. Logical Operations - Motivation 2/8/18

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

2. What are the two main components to the CPU and what do each of them do? 3. What is the difference between a compiler and an interpreter?

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

2. What are the two main components to the CPU and what do each of them do? 3. What is the difference between a compiler and an interpreter?

SOFTWARE DEVELOPMENT 1. Operators 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

Java I/O and Control Structures

BRANCHING if-else statements

Chapter 3. Selections. Program Listings

Building Java Programs

Review. Primitive Data Types & Variables. String Mathematical operators: + - * / % Comparison: < > <= >= == int, long float, double boolean char

CMPT 125: Lecture 4 Conditionals and Loops

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

JAVA Programming Concepts

Chapter 2 Elementary Programming

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

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.

Repetition, Looping. While Loop

bool bool - either true or false

CT 229 Java Syntax Continued

Chapter 2: Using Data

Java Simple Data Types

Transcription:

Selections CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1

Motivation If you assigned a negative value for radius in ComputeArea.java, then you don't want the program to compute the area. 2

The boolean Type and Operators Often in a programs you need to compare values: if x is greater than y Java provides six comparison operators (relational operators) to compare two values: <, <=, >, >=, == and!= The result of the comparison is a Boolean value: true or false. boolean b = (1 > 2); 3

Comparison Operators Operator Name < less than <= less than or equal to > greater than >= greater than or equal to == equal to!= not equal to 4

One-way if Statements if (booleanexpression) { statement(s); } if (radius >= 0) { } area = radius * radius * PI; System.out.println("The area" +" for the circle of radius " + radius + " is " + area); Boolean Expression false (radius >= 0) false true true Statement(s) area = radius * radius * PI; System.out.println("The area for the circle of " + "radius " + radius + " is " + area); 5 (A) (B)

One-way if Statements Condition containment necessary! if i > 0 { System.out.println("i is positive"); } (a) Wrong if (i > 0) { System.out.println("i is positive"); } (b) Correct No block containment necessary! if (i > 0) { System.out.println("i is positive"); } (a) Equivalent if (i > 0) System.out.println("i is positive"); (b) 6

Two-way if Statement if (boolean-expression) { statement(s)-for-the-true-case; } else { statement(s)-for-the-false-case; } true Statement(s) for the true case Boolean Expression false Statement(s) for the false case 7

if...else Example if (radius >= 0) { area = radius * radius * 3.14159; System.out.println("The area for the" + " circle of radius " + radius + " is " + area); } else System.out.println("Negative input"); 8

Multiple Alternative if Statements if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; Equivalent if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; 9

Trace if-else statement Suppose score is 70.0 The condition is false if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; 10

Trace if-else statement Suppose score is 70.0 The condition is false if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; 11

Trace if-else statement Suppose score is 70.0 The condition is true if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; 12

Trace if-else statement Suppose score is 70.0 grade is C if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; 13

Trace if-else statement Suppose score is 70.0 Exit the if statement if (score >= 90.0) grade = 'A'; else if (score >= 80.0) grade = 'B'; else if (score >= 70.0) grade = 'C'; else if (score >= 60.0) grade = 'D'; else grade = 'F'; 14

if else The else clause matches the most recent if clause in the same block. int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); Equivalent int i = 1; int j = 2; int k = 3; if (i > j) if (i > k) System.out.println("A"); else System.out.println("B"); (a) This does not print anything! (b) 15

if else To force the else clause to match the first if clause, you must add a pair of braces: int i = 1; int j = 2; int k = 3; if (i > j) { if (i > k) System.out.println("A"); } else System.out.println("B"); This code prints B. 16

Common Error Adding a semicolon at the end of an if clause is a common mistake. if (radius >= 0); { Wrong area = radius*radius*pi; System.out.println( "The area for the circle of radius " + radius + " is " + area); } It is not a compilation error or a runtime error, it is a logic error This error often occurs when you use the next-line block style 17

What s wrong here? System.out.print("Enter your total cholesterol level: "); int totalcholesterol= keyboard.nextint(); if (totalcholesterol>= 200) System.out.println("Your cholesterol is too high."); System.out.println("You need to lower that."); else System.out.println("Good, eat away!"); 18

What s wrong here? System.out.print("Enter your total cholesterol level: "); int totalcholesterol= keyboard.nextint(); if (totalcholesterol>= 200) System.out.println("Your cholesterol is too high."); System.out.println("You need to lower that."); else // COMPILER ERROR HERE System.out.println("Good, eat away!"); 19

What s wrong here? System.out.print("Enter your total cholesterol level: "); int totalcholesterol= keyboard.nextint(); if (totalcholesterol>= 200) { // Now it is correct System.out.println("Your cholesterol is too high."); System.out.println("You need to lower that."); } else System.out.println("Good, eat away!"); 20

Why is this worse? System.out.print("Enter your total cholesterol level:"); int totalcholesterol= keyboard.nextint(); if (totalcholesterol>= 200) System.out.println("Your cholesterol is too high."); System.out.println("You need to lower that."); // No compiler error // Bug, logical error 21

Why is this worse? System.out.print("Enter your total cholesterol level: "); int totalcholesterol= keyboard.nextint(); if (totalcholesterol>= 200){ // correct } System.out.println("Your cholesterol is too high."); System.out.println("You need to lower that."); 22

What about complex conditions? For example: Computing Taxes: the US federal income tax is calculated based on the filing status and taxable income (multiple/complex logical conditions) There are four filing statuses: single filers, married filing jointly, married filing separately, and head of household. Marginal Tax Rate Single (0) Married Filing Jointly or Qualified Widow(er) (1) Married Filing Separately (2) Head of Household (3) 10% $0 $8,350 $0 $16,700 $0 $8,350 $0 $11,950 15% $8,351 $33,950 $16,701 $67,900 $8,351 $33,950 $11,951 $45,500 25% $33,951 $82,250 $67,901 $137,050 $33,951 $68,525 $45,501 $117,450 28% $82,251 $171,550 $137,051 $208,850 $68,525 $104,425 $117,451 $190,200 33% $171,551 $372,950 $208,851 $372,950 $104,426 $186,475 $190,201 - $372,950 35% $372,951+ $372,951+ $186,476+ $372,951+ 23

Logical Operators Operator Name! not && and or ^ exclusive or 24

Truth Table for Operator! p!p Example (assume age = 24, gender = 'F') true false false true!(age > 18) is false, because (age > 18) is true.!(gender!= 'F') is true, because (grade!= 'F') is false. 25

Truth Table for Operator && p1 p2 p1 && p2 false false false false true false true false false true true true Example (assume age = 24, gender = 'F') (age > 18) && (gender == 'F') is true, because (age > 18) and (gender == 'F') are both true. (age > 18) && (gender!= 'F') is false, because (gender!= 'F') is false. 26

Truth Table for Operator p1 p2 p1 p2 false false false false true true true false true true true true Example (assume age = 24, gender = 'F') (age > 34) (gender == 'F') is true, because (gender == 'F') is true. (age > 34) (gender == 'M') is false, because (age > 34) and (gender == 'M') are both false. 27

Truth Table for Operator ^ p1 p2 p1 ^ p2 false false false false true true true false true true true false Example (assume age = 24, gender = 'F') (age > 34) ^ (gender == 'F') is true, because (age > 34) is false but (gender == 'F') is true. (age > 34) ^ (gender == 'M') is false, because (age > 34) and (gender == 'M') are both false. 28

Logical Operators Examples What is the result? boolean result; result = (5 <= 9); result =!(5 <= 9); result = (3.9 > 3.19); result = ('a' == 'A'); result = (5 <= 9 && 8 > 9); result = (5 <= 9 8 > 9); 29

Logical Operators Examples System.out.println("Is " + number + " divisible by 2 and 3? " + ((number % 2 == 0) && (number % 3 == 0))); System.out.println("Is " + number + " divisible by 2 or 3? " + ((number % 2 == 0) (number % 3 == 0))); System.out.println("Is " + number + " divisible by 2 or 3, but not both? " + ((number % 2 == 0) ^ (number % 3 == 0))); 30

Determining Leap Year This program first prompts the user to enter a year as an int value and checks if it is a leap year. A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400. (year % 4 == 0 && year % 100!= 0) year % 400 == 0 31

The unconditional & and Operators The & operator works exactly the same as the && operator, and the operator works exactly the same as the operator with one exception: the & and operators always evaluate both operands 32

The unconditional & and Operators If x is 1, what is x after these expressions: (x > 1) && (x++ < 10) 1 (x > 1) & (x++ < 10) 2 (1 == x) (10 > x++)? 1 (1 == x) (10 > x++)? 2 33

switch Statements switch (var) { case 0:...; break; case 1:...; break; case 2:...; break; case 3:...; break; default:...; } 34

Compute tax for married file separately switch Statement Flow Chart var is 0 break var is 1 break var is 2 break var is 3 break default Next Statement 35

switch Statement Rules 36 char, byte, short, int, String value1,..., and valuen are constant expressions of the same data type as the value of the switchexpression constant = they cannot contain variables in the expression, such as x+y switch (switch-expression) { } case value1: case value2: case valuen: default: statement(s)1; break; statement(s)2; break; statement(s)n; break; statement(s);

switch Statement Rules break is optional, but it terminates the remainder of the switch statement default is optional - executed when none of the specified cases matches the switch-expression. 37 switch (switch-expression) { } case value1: case value2: execution in sequential order case valuen: default: statement(s)1; break; statement(s)2; break; statement(s)n; break; statement(s);

Trace switch statement Suppose ch is 'a': switch (ch) { case 'a': case 'b': case 'c': } 38

Trace switch statement ch is 'a': switch (ch) { case 'a': case 'b': case 'c': } 39

Trace switch statement Execute this line switch (ch) { case 'a': case 'b': case 'c': } 40

Trace switch statement Execute this line switch (ch) { case 'a': case 'b': case 'c': } 41

Trace switch statement Execute this line switch (ch) { case 'a': case 'b': case 'c': } 42

Trace switch statement switch (ch) { case 'a': case 'b': case 'c': } 43

Trace switch statement 2 Suppose ch is 'a': switch (ch) { case 'a': } case 'b': case 'c': break; break; 44

Trace switch statement 2 Execute this line switch (ch) { case 'a': } case 'b': case 'c': break; break; 45

Trace switch statement 2 Execute this line switch (ch) { case 'a': } case 'b': case 'c': break; break; 46

Trace switch statement 2 switch (ch) { case 'a': } case 'b': case 'c': break; break; 47

Conditional Operator if (x > 0) y = 1; else y = -1; is equivalent to: y = (x > 0)? 1 : -1; Conditional operator: boolean-expression? expression1 : expression2 For example: System.out.println((num % 2 == 0)? num + " is even" :num + " is odd"); 48

Operator Precedence 49 var++, var-- +, - (Unary plus and minus), ++var,--var (type) Casting! (Not) *, /, % (Multiplication, division, and remainder) +, - (Binary addition and subtraction) <, <=, >, >= (Comparison) ==,!=; (Equality) ^ (Exclusive OR) && (Conditional AND) Short-circuit AND (Conditional OR) Short-circuit OR =, +=, -=, *=, /=, %= (Assignment operator) All binary operators except assignment operators are leftassociative.

Example Applying the operator precedence and associativity rule, the expression 3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows: 50 3 + 4 * 4 > 5 * (4 + 3) - 1 (1) inside parentheses first 3 + 4 * 4 > 5 * 7 1 (2) multiplication 3 + 16 > 5 * 7 1 (3) multiplication 3 + 16 > 35 1 (4) addition 19 > 35 1 (5) subtraction 19 > 34 (6) greater than false

Operator Associativity The assignment operators are right-associative: a = b += c = 5 is equivalent to a = (b += (c = 5)) 51

52 ChangeMaker Example Revisited System.out.print("Input change amount (1-99):"); originalamount= scanner.readint(); if (originalamount< 1 originalamount> 99) System.out.println("ERROR: Out of range."); else{ numquarters= originalamount/ 25; remainder = originalamount% 25; numdimes= remainder / 10; remainder = remainder % 10; numnickels= remainder / 5; numpennies= remainder % 5; if (numquarters!= 0) // Do not print if zero System.out.println(numQuarters+ " quarters"); if (numdimes!= 0)// Do not print if zero System.out.println(numDimes+ " dimes"); if (numnickels!= 0)// Do not print if zero System.out.println(numNickels+ " nickels"); if (numpennies!= 0)// Do not print if zero System.out.println(numPennies+ " pennies"); }

ChangeMaker Example Revisited Nested ifs: if (numquarters!= 0){ // Do not print if zero System.out.print(numQuarters+ " quarter"); if (numquarters== 1) // Do not print s if one System.out.println( ); else System.out.println("s"); // print s if more } 53