Conditional Statements. 15-110 Summer 2010 Margaret Reid-Miller

Similar documents
CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

The if Statement and Practice Problems

Statements and Control Flow

J a v a Quiz (Unit 3, Test 0 Practice)

Example of a Java program

While and Do-While Loops Summer 2010 Margaret Reid-Miller

Object Oriented Software Design

Sample CSE8A midterm Multiple Choice (circle one)

Conditions & Boolean Expressions

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Chapter 2 Introduction to Java programming

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

COMP 110 Prasun Dewan 1

Chapter 8 Selection 8-1

6. Control Structures

Topic 11 Scanner object, conditional execution

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

1.3 Conditionals and Loops

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

Moving from CS 61A Scheme to CS 61B Java

1.00/ Session 2 Fall Basic Java Data Types, Control Structures. Java Data Types. 8 primitive or built-in data types

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Chapter 5. Selection 5-1

Conditionals (with solutions)

Lecture 2 Notes: Flow of Control

Iteration CHAPTER 6. Topic Summary

Variables, Constants, and Data Types

CS 106 Introduction to Computer Science I

Statements and Control Flow

CS 111 Classes I 1. Software Organization View to this point:

Selection Statements

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

VB.NET Programming Fundamentals

Object Oriented Software Design

Building Java Programs

CASCADING IF-ELSE. Cascading if-else Semantics. What the computer executes: What is the truth value 1? 3. Execute path 1 What is the truth value 2?

Introduction to Java

Boolean Expressions & the if Statement

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Introduction to Computer Programming, Spring Term 2014 Practice Assignment 3 Discussion

Java Basics: Data Types, Variables, and Loops

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

PL / SQL Basics. Chapter 3

Two-Dimensional Arrays Summer 2010 Margaret Reid-Miller

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

Understanding class definitions

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

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

LOOPS CHAPTER CHAPTER GOALS

Chapter 14: Boolean Expressions Bradley Kjell (Revised 10/08/08)

Python Lists and Loops

Boolean Expressions 1. In C++, the number 0 (zero) is considered to be false, all other numbers are true.

Building Java Programs

Chapter 3 Operators and Control Flow

Exercise 1: Python Language Basics

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Part I. Multiple Choice Questions (2 points each):

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

AP Computer Science Java Subset

The first program: Little Crab

JavaScript: Control Statements I

Introduction to Python

5.2 Q2 The control variable of a counter-controlled loop should be declared as: a.int. b.float. c.double. d.any of the above. ANS: a. int.

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Java Interview Questions and Answers

2 The first program: Little Crab

ECE 122. Engineering Problem Solving with Java

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Object-Oriented Design Lecture 4 CSU 370 Fall 2007 (Pucella) Tuesday, Sep 18, 2007

Introduction to Java Lecture Notes. Ryan Dougherty

Programming Languages CIS 443

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

Arrays. Introduction. Chapter 7

csce4313 Programming Languages Scanner (pass/fail)

CS106A, Stanford Handout #38. Strings and Chars

Translating C code to MIPS

3/13/2012. Writing Simple C Programs. ESc101: Decision making using if-else and switch statements. Writing Simple C Programs

This loop prints out the numbers from 1 through 10 on separate lines. How does it work? Output:

VISUAL GUIDE to. RX Scripting. for Roulette Xtreme - System Designer 2.0

Bash shell programming Part II Control statements

While Loop. 6. Iteration

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

Pemrograman Dasar. Basic Elements Of Java

Software Engineering Techniques

Building Java Programs

Basic Programming and PC Skills: Basic Programming and PC Skills:

(b) You draw two balls from an urn and track the colors. When you start, it contains three blue balls and one red ball.

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

Accentuate the Negative: Homework Examples from ACE

Answers to Review Questions Chapter 7

Computer Programming I

Introduction to Python

Program Logic to Java GEEN163

Moving from C++ to VBA

CS1020 Data Structures and Algorithms I Lecture Note #1. Introduction to Java

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

Transcription:

Conditional Statements 15-110 Summer 2010 Margaret Reid-Miller

Conditional statements Within a method, we can alter the flow of control (the order in which statements are executed) using either conditionals or loops. The conditional statements if, if-else, and switch allow us to choose which statement will be executed next. Each choice or decision is based on the value of a boolean expression (also called the condition). Summer 2010 15-110 (Reid-Miller) 2

The if statement If we have code that we sometimes want to execute and sometimes we want to skip we can use the if statement. The form of the if statement is if (boolean_expression) statement If boolean_expression evaluates to true, then statement is executed. If boolean_expression evaluates to false, then statement is skipped. Note that the boolean_expression enclosed in parentheses must evaluate to true or false. Summer 2010 15-110 (Reid-Miller) 3

The if Flowchart boolean_expression false true statement Summer 2010 15-110 (Reid-Miller) 4

if-statement Examples!if (count > 0)! average = total / count;! if (age >= 26)!!if (haslicense == true)! Or simply haslicense!system.out.println( You may rent a car. );! daysinfeb = 28;!! if (isleapyear) {! daysinfeb = 29;! System.out.println(year + is a leap year. );! Summer 2010 15-110 (Reid-Miller) 5

The if Statement The statement in the if statement can be any Java statement: A simple statement A compound statement, such as an if statement A block statement, a group of statements enclosed in braces {} if (zipcode == 15213) {! city = Pittsburgh ;! state = PA ;! Proper indentation becomes essential! Summer 2010 15-110 (Reid-Miller) 6

The if-else Statement If we want to choose between two alternative we use the if/else statement: if (boolean_expression)! statement1! else!! statement2! If boolean_expression evaluates to true, then statement1 is executed. If boolean_expression evaluates to false, then statement2 is executed. Summer 2010 15-110 (Reid-Miller) 7

The if-else Flowchart true boolean_expression false! statement1 statement2 Summer 2010 15-110 (Reid-Miller) 8

if-else Statement Examples!if (temperature <= 32.0) {!! forecast = SNOW ;!! else {! forecast = RAIN ;!!} The then clause The else clause!if (count > 0) {!! average = total / count;!! else {!! System.out.println( No data to average. );!!} Summer 2010 15-110 (Reid-Miller) 9

Common Error 1 When you want to test if the value of a variable is in a range.!if (0 < temperature < 100) {!! state = LIQUID ;!! WRONG!! if (0 < temperature && temperature < 100) {!!state = LIQUID ;! Correct Summer 2010 15-110 (Reid-Miller) 10

Common Error 2 When you want to test if the value of a variable is one of two alternates. WRONG!!!if (choice == M L ) {!! System.out.println( You re correct! );!! if (choice == M choice == L ) {!! System.out.println( You re correct! );! Correct Summer 2010 15-110 (Reid-Miller) 11

The Dangling else Problem When an if statement is nested inside the then clause of another if statement, the else clause is paired with the closest if statement without an else clause. if (x > 0)! if (y > 0)! color = red ;! else! color = blue ; Misleading indentation Summer 2010 15-110 (Reid-Miller) 12

The Dangling else Problem In reality it is if (x > 0)! if (y > 0)! color = red ;! else! color = blue ; y x Summer 2010 15-110 (Reid-Miller) 13

The Dangling else Problem Use braces to pair else with the outer if if (x > 0) {! if (y > 0)! color = red ;! else {! color = blue ;! y x Compare flowcharts! Summer 2010 15-110 (Reid-Miller) 14

Multiple Alternatives Determine if a number is positive, negative, or zero: if (value < 0) {!!System.out.println( Value is negative. );! if (value == 0) {!!System.out.println( Value is zero. );! if (value > 0) {!!System.out.println( Value is positive. );! Computer thinks any combination of the three statements can be executed. Summer 2010 15-110 (Reid-Miller) 15

Multiple Alternatives Determine if a number is positive, negative, or zero if (value < 0) {!! System.out.println( Value is negative. );! else {!! if (value == 0) {!!! System.out.println( Value is zero. );!! else {!!! if (value > 0) {!!!! System.out.println( Value is positive. );!!!! At most one statement is executed. Leads to lots of indentation. Summer 2010 15-110 (Reid-Miller) 16

Multiple Alternatives Determine if a number is positive, negative, or zero if (value < 0) {!! System.out.println( Value is negative. );! { else {!! if (value == 0) {!!! System.out.println( Value is zero. );!! else {!!! if (value > 0) {!!!! System.out.println( Value is positive. );!!!! Remove unnecessary brackets and re-indent Summer 2010 15-110 (Reid-Miller) 17

Multiple Alternatives Determine if a number is positive, negative, or zero: if (value < 0) {!! System.out.println( Value is negative. );! else if (value == 0) {!!!System.out.println( Value is zero. );! else if (value > 0) {!!!System.out.println( Value is positive. );! At most one statement is executed. Each choice, however, is at same indentation. Summer 2010 15-110 (Reid-Miller) 18

Multiple Alternatives Determine if a number is positive, negative, or zero: if (value < 0) {!!System.out.println( Value is negative. );! else if (value == 0) {!!!System.out.println( Value is zero. );! else { // value must be positive!!!system.out.println( Value is positive. );! It is clear, exactly one statement is executed. Summer 2010 15-110 (Reid-Miller) 19

Multiple Alternatives: Assignments Determine the fare: $2 for a child (no more than 11 years), $3 for a senior (at least 65 years), or $5 for an adult. int fare;! if (age ) {!!fare = 2;! fare must be defined before the if statement else if (age ) { //!!fare = 5;! else { //! last clause must be!fare = 3;! else with no if System.out.println( Your fare is $ + fare);! Summer 2010 15-110 (Reid-Miller) 20

Exercise Write a method that prints how many of n1, n2, and n3 are odd: public void printnumodd(int n1, int n2, int n3) {! Summer 2010 15-110 (Reid-Miller) 21

Exercise Write a method that print whether die1 and die2 are doubles, cat s eyes (two 1 s) or neither of these. public void printdoubles(int die1, int die2) {! Summer 2010 15-110 (Reid-Miller) 22

Programming Style Single-line if statement: if (y > 0) color = red ;! Multi-line if statement: if (zipcode == 15213) {! city = Pittsburgh ;! state = PA ;! } The if-else statement: if (temperature <= 32.0) {! forecast = SNOW ;! else {! forecast = RAIN ;! Multiple alternatives: if (value < 0) {! valuetype = negative ;! else if (value == 0) {! valuetype = zero ;! else { // no if here!!! valuetype = positive ;! Summer 2010 15-110 (Reid-Miller) 23

Testing For Equality For primitive values use == for equality testing. For objects, use the equals method for testing equal contents. The argument must be the same type as the object on which equals() is called. The method returns true or false depending on whether both objects are equal or not. For example, let day be an int variable and month be a String variable.! if (day == 1 && month.equals( APRIL )) {!! System.out.println( It s April Fool s Day );! } Two String objects are equal if they have exactly the same characters, including case and number of characters. Summer 2010 15-110 (Reid-Miller) 24

Testing for Equality with doubles Which statement will Java print? double x = Math.sqrt(2.0);! double y = x * x;! if (y == 2.0) {!!System.out.println("sqrt(2) * sqrt(2) is 2");! else {!!System.out.println("sqrt(2) * sqrt(2)!!!!!+ is not 2. It is " + y);! } Never test for exact equality with floating point numbers! Summer 2010 15-110 (Reid-Miller) 25

Testing for Equality with doubles Because of round-off errors, you should test if the numbers are close. double tolerance = 1.0e-10; double x = Math.sqrt(2.0);! double y = x * x;! if (Math.abs(y - 2.0) < tolerance) {!!System.out.println("sqrt(2) * sqrt(2) is 2");! else {!!System.out.println("sqrt(2) * sqrt(2)!!!!!+ is not 2. It is " + y);! Summer 2010 15-110 (Reid-Miller) 26

Short-Circuit Evaluation Short circuit evaluation (or lazy evaluation) : If the first conditional in an && expression is false, Java does not execute the second conditional. Example:! if (liters > 0 && total/liters > threshold) {!! System.out.println( WARNING: Exceeds threshold );! } What if the expression was an expression? Summer 2010 15-110 (Reid-Miller) 27

The switch statement If an if/else statement with multiple alternatives compares an int or char variable or expression against several constants you can use a switch statement. Example:!switch (suitaschar) {!!case C : suitasname = Clubs ; break;!!case D : suitasname = Diamonds ; break;!!case H : suitasname = Hearts ; break;!!case S : suitasname = Spades ; break;!!default: suitasname = Unknown ;! Summer 2010 15-110 (Reid-Miller) 28