Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Simple Control Flow: if-else statements

Similar documents
Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Methods

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Testing and Debugging

++x vs. x++ We will use these notations very often.

Lab Exercise 1. Objectives: Part 1. Introduction

Oct Decision Structures cont d

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

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

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

Scanner Objects. Zheng-Liang Lu Java Programming 82 / 133

Logic is the anatomy of thought. John Locke ( ) This sentence is false.

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 88 / 133

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

Arithmetic Compound Assignment Operators

while (/* array size less than 1*/){ System.out.print("Number of students is invalid. Enter" + "number of students: "); /* read array size again */

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to define and invoke void and return java methods

1 class Lecture3 { 2 3 "Selections" // Keywords 8 if, else, else if, switch, case, default. Zheng-Liang Lu Java Programming 89 / 137

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

Midterm Examination (MTA)

Section 002 Spring CS 170 Exam 1. Name (print): Instructions:

Programming with Java

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Arrays

IEEE Floating-Point Representation 1

Question: Total Points: Score:

JAVA OPERATORS GENERAL

Lab1 Solution. Lab2 Solution. MathTrick.java. CoinFlip.java

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

CS212 Midterm. 1. Read the following code fragments and answer the questions.

Java Simple Data Types

Introduction to Computer Science Unit 2. Notes

2.2 - Making Decisions

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

Decisions in Java The IF Statement. In performing a task, we often want to take one of two possible actions depending on the conditions at the time.

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

Computational Expression

Web-CAT submission URL: CAT.woa/wa/assignments/eclipse

Tutorial 03. Exercise 1: CSC111 Computer Programming I

AP COMPUTER SCIENCE A

Place your name tag here

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

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

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

Introduction to Computer Science, Shimon Schocken, IDC Herzliya. Lectures Control Structures

CS1150 Principles of Computer Science Boolean, Selection Statements

CAT.woa/wa/assignments/eclipse

H212 Introduction to Software Systems Honors

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

Eng. Mohammed S. Abdualal

Chapter 3 Selections. 3.1 Introduction. 3.2 boolean Data Type

Decisions (If Statements) And Boolean Expressions

Example. Write a program which sums two random integers and lets the user repeatedly enter a new answer until it is correct.

What methods does the String class provide for ignoring case sensitive situations?

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

b. Suppose you enter input from the console, when you run the program. What is the output?

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

Java Simple Data Types

Key Java Simple Data Types

Section 004 Spring CS 170 Exam 1. Name (print): Instructions:

In this chapter, you will:

Prof. Navrati Saxena TA: Rochak Sachan

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

Question: Total Points: Score:

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

Programming Basics. Digital Urban Visualization. People as Flows. ia

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

For that purpose, java provides control structures that serve to specify what has to be done by our program, when and under which circumstances.

CS 231 Data Structures and Algorithms Fall Event Based Programming Lecture 06 - September 17, Prof. Zadia Codabux

Selenium Class 9 - Java Operators

COMP-202 Unit 4: Programming with Iterations

CONDITIONAL EXECUTION

COMP-202: Foundations of Programming. Lecture 6: Conditionals Jackie Cheung, Winter 2016

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

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

COMP 202 Java in one week

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

Repetition, Looping. While Loop

Values in 2 s Complement

Lecture 8 " INPUT " Instructor: Craig Duckett

Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 45 Obtained Marks:

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

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

Object Oriented Programming. Java-Lecture 6 - Arrays

Elementary Programming

CS141 Programming Assignment #6

CIS 1068 Program Design and Abstraction Spring2016 Midterm Exam 1. Name SOLUTION

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

Elementary Programming

Claremont McKenna College Computer Science

false, import, new 1 class Lecture2 { 2 3 "Data types, Variables, and Operators" 4

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Computer Programming, I. Laboratory Manual. Experiment #7. Methods

Example Program. public class ComputeArea {

New York University Introduction to Computer Science Exam Sample Problems 2013 Andrew I. Case. Instructions:

Loops. CSE 114, Computer Science 1 Stony Brook University

Full file at

Chapter 3 Selection Statements

Arithmetic Compound Assignment Operators

Lesson 7 Part 2 Flags

Chapter 3. Selections

Expression statements are formed by adding a semicolon to the end of certain types of expressions.

Transcription:

WIT COMP1000 Simple Control Flow: if-else statements

Control Flow Control flow is the order in which program statements are executed So far, all of our programs have been executed straight-through from the first statement to the last In general, you will need more complex control flow For example, to choose between two (or more) possibilities WIT COMP1000 2

Branching Human Example: greeting two different people 'ello Harry! 'ello Hermione! WIT COMP1000 3

Basics Steps Thought process:» Whom am I looking at?» If I am looking at Harry Potter Say 'ello Harry!» If I am looking at Hermione Granger Say 'ello Hermione! Java uses if-else statements to choose between alternatives WIT COMP1000 4

if-else Example: if (user_id == 1742) { System.out.println("'ello Harry!"); else { System.out.println("'ello Hermione!"); Generic form: if (BOOLEAN EXPRESSION) { YES/TRUE STATEMENTS else { NO/FALSE STATEMENTS WIT COMP1000 5

if-else Each if-else statement allows your program to do one of two different things In other words, you EITHER use one set of statements OR you use the other The statements in between the { for the if and the else can contain any code you want, just like code that is not inside an if-else» Even other if-else statements! WIT COMP1000 6

Boolean Expressions Boolean expressions (like boolean variables) are either true or false, and are composed of comparisons Comparison Operators == Equal To if (x == 10)!= Not Equal To if (x!= 5) < Less Than if (hours < 40) <= Less Than or Equal To if (dollars <= 100) > Greater Than if (dollars > 100) >= Greater than or Equal To if (hours >= 40) WIT COMP1000 7

Example import java.util.scanner; public class ClassExamples { public static void main(string[] args) { Scanner input = new Scanner(System.in); double input_value; System.out.print("Please enter a number: "); input_value = input.nextdouble(); if (input_value > 100) { System.out.println("That is greater than 100."); else { System.out.println("That is less than or equal to 100."); System.out.println("Thank you!"); WIT COMP1000 8

Control Flow So, if the if condition is true, the statements between the next curly braces are executed, then it skips down past the else curly braces and continues executing If the if condition is false, the statements between the if braces are ignored, then the statements between the else braces are executed, then it continues executing whatever is next WIT COMP1000 9

import java.util.scanner; Execution Example public class ClassExamples { public static void main(string[] args) { Scanner input = new Scanner(System.in); int x = 15; 15 > 0 is true if (x > 0) { System.out.println("x is positive"); else { System.out.println("x in non-positive"); System.out.println("Thank you, and good night."); WIT COMP1000 10

Exercise Write a program that reads an integer from the user and determines whether or not the integer is even (evenly divisible by 2) or odd (not evenly divisible by 2) WIT COMP1000 11

Answer import java.util.scanner; public class ClassExamples { public static void main(string[] args) { Scanner input = new Scanner(System.in); int value; int remainder; System.out.print("Enter an integer: "); value = input.nextint(); remainder = value % 2; if (remainder == 0) { System.out.println(value + " is even"); else { System.out.println(value + " is odd"); WIT COMP1000 12

String Equality Recall that String variables are actually objects which means that they follow slightly different rules If you want to compare two String variables together, you must use the String equals() method» Example: string_variable.equals("something") You can also compare two String variables» Example: str1.equals(str2) WIT COMP1000 13

String Comparison Example Scanner input = new Scanner(System.in); System.out.print("Enter a name: "); String user = input.next(); if (user.equals("harry")) { System.out.println("'ello Harry!"); else { System.out.println("'ello Hermione!"); WIT COMP1000 14

Omitting Braces You can omit the curly braces after an if or else ONLY if there is exactly one statement Example: if (hours_worked > 8) System.out.println("It's quittin' time!"); else System.out.println("Get back to work!"); I recommend always using the braces» Easier to read» Less chance of errors if you add more statements later on WIT COMP1000 15

Multiple Choices Standard if-else statements give you two choices You can have more choices by adding else if statements in between the if and else Any number of else if statements can be added after an if statement Each will be tested in order until one of the conditions is true, and the else statements will only run if none of the conditions are true You can always omit the else statement if you want (even if you have no else if statements) WIT COMP1000 16

else if Statements if (EXPRESSION1) { //run statements if expression 1 is true else if (EXPRESSION2) { //run statements if expressions 1 is false, //and expression 2 is true else { //run statements if both expressions are false WIT COMP1000 17

Example if (x > 10) { System.out.println("x is greater than 10"); else if (x < 5) { System.out.println("x is less than 5"); else { System.out.println("x is between 5 and 10, inclusive"); WIT COMP1000 18

Example if (x > 10) { System.out.println("x is greater than 10"); else if (x > 5) { System.out.println("x is between 6 and 10, inclusive"); else { System.out.println("x is less than or equal to 5"); WIT COMP1000 19

Multiple else if Statements if (x > 10) { System.out.println("x is greater than 10"); else if (x > 5) { System.out.println("x is between 6 and 10, inclusive"); else if (x > 0) { System.out.println("x is between 1 and 5, inclusive"); else { System.out.println("x is less than 1"); WIT COMP1000 20

Exercise Write a program that reads a numeric score from the user and outputs a letter grade» If the score is >=90, output A» If the score is >=80 and <90, output B» If the score is >=70 and <80, output C» If the score is >=60 and <70, output D» If the score is <60, output F WIT COMP1000 21

Answer Scanner input = new Scanner(System.in); int score; System.out.print("Enter your score: "); score = input.nextint(); System.out.print("Letter Grade: "); if (score >= 90) { System.out.println("A"); else if (score >= 80) { System.out.println("B"); else if (score >= 70) { System.out.println("C"); else if (score >= 60) { System.out.println("D"); else { System.out.println("F"); WIT COMP1000 22

Complex Boolean Expressions Multiple comparisons can be combined with the and and or operators && is the and operator» Example: (hours > 20) && (hours <= 40)» Entire expression is true only if both comparisons are true, and false if either is false is the or operator» Example: (x < 17) (y < 22)» Entire expression is true if either comparison is true, and false only if both are false WIT COMP1000 23

Examples // assume x = 5 (x >= 10) && (x!= 12) // assume x = 48 (x >= 10) && (x!= 12) // false, (5 >= 10) is false, so it doesn t matter if (x!= 12) is true // true, (48 >= 10) is true and (48!= 12) is true // assume x = 12 (x >= 10) && (x!= 12) // false, (12 >= 10) is true but (12!= 12) is false // assume x = 12 (x >= 10) (x!= 12) // assume x = 5 (x >= 10) (x!= 12) // true, (12 >= 10) is true, so it doesn t matter if (x!= 12) is true // true, (5 >= 10) is false, but (5!= 12) is true WIT COMP1000 24

Time Example Scanner input = new Scanner(System.in); int hours; System.out.print("Enter the hours in 24 hour notation: "); hours = input.nextint(); if ((hours >= 1) && (hours <= 11)) { System.out.println("That is " + hours + "am"); else if ((hours >= 13) && (hours <= 23)) { hours = hours - 12; System.out.println("That is " + hours + "pm"); else if (hours == 12) { System.out.println("That is " + hours + "pm"); else if (hours == 0) { hours = hours + 12; System.out.println("That is " + hours + "am"); else { System.out.println("That is not a valid hour!"); WIT COMP1000 25

Pin Hole Camera Example Scanner input = new Scanner(System.in); double focal_length; // f double object_distance; // o double image_distance; // i double step1; System.out.print("Enter the focal length: "); focal_length = input.nextdouble(); System.out.print("Enter the object distance: "); object_distance = input.nextdouble(); if ((focal_length == 0) (object_distance == 0)) { System.out.println("Please enter non-zero values."); System.exit(0); WIT COMP1000 26 // solve the thin lens equation: 1/i = 1/f - 1/o step1 = (1/focal_length) - (1/object_distance); if (step1 == 0) { System.out.println("The image is infinitely far away."); else { image_distance = 1 / step1; System.out.println("The image distance is " + image_distance + ".");

Sanitizing User Inputs When you get input from the user, you should always check that the values they entered are reasonable» Otherwise you might have a GIGO scenario: Garbage In, Garbage Out» That is, if they input "bad" values into your program then they will get "bad" results You can stop your program early by adding a new statement: System.exit(0);» Typically after you detect an error or bad input value» When executed, your program end immediately WIT COMP1000 27

Exercise Write a program that reads two exam scores from the user. If both exam scores are greater than 90, print "Way to go!". If either exam score is less than 70, print "Study more!". Otherwise, print "Keep it up!". WIT COMP1000 28

Answer Scanner input = new Scanner(System.in); int exam1; int exam2; System.out.println("Enter your two exam scores:"); exam1 = input.nextint(); exam2 = input.nextint(); if ((exam1 > 90) && (exam2 > 90)) { System.out.println("Way to go!"); else if ((exam1 < 70) (exam2 < 70)) { System.out.println("Study more!"); else { System.out.println("Keep it up!"); WIT COMP1000 29

Common Mistakes When using comparison operators, always use == for checking equality, never =» Some situations will not give you any errors or warnings, but your program will not operate as you expect You can not put multiple comparisons together without the and or or operators» Incorrect: if (10 < x < 15)» Correct: if ((10 < x) && (x < 15)) WIT COMP1000 30

Take Home Points Use if-else statements when you need to choose between two or more possibilities Always put boolean expressions in parentheses Multiple expressions can be put together with the and (&&) and or ( ) operators» Always put each comparison in its own set of parentheses Always use == for testing equality, never = WIT COMP1000 31