Flow of Control. Chapter 3

Similar documents
Flow of Control. Chapter 3

Flow of Control. Chapter 3

Flow of Control. Chapter 3. Chapter 3 1

CONDITIONAL EXECUTION: PART 2

Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Flow of Control. Chapter

Flow of Control. Chapter 3 Part 3 The Switch Statement

Chapter 3. Flow of Control. Branching Loops exit(n) method Boolean data type and expressions

Topics. Chapter 5. Equality Operators

Handout 4 Conditionals. Boolean Expressions.

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

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

Oct Decision Structures cont d

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

Flow of Control. 3.1 Branching Mechanism Boolean Expressions Loops Debugging 144

COMP Flow of Control: Branching 2. Yi Hong May 19, 2015

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

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

Control Structures in Java if-else and switch

In this chapter, you will:

Lesson 7 Part 2 Flags

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

Chapter 3. Selections

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

Control Structures in Java if-else and switch

Chapter 4: Control Structures I

Programming: Java. Chapter Objectives. Control Structures. Chapter 4: Control Structures I. Program Design Including Data Structures

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

Decisions (If Statements) And Boolean Expressions

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

Conditional Programming

Conditionals and Loops

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

Java Coding 2. Decisions, decisions!

Chapter 4: Conditionals and Loops

Logic & program control part 2: Simple selection structures

Basic Computation. Chapter 2

PROGRAMMING STYLE. Fundamentals of Computer Science I

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

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.

Full file at

COMP 202 Java in one week

Pace University. Fundamental Concepts of CS121 1

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

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

AP Computer Science A

Basic Computation. Chapter 2

Control Structures: if and while A C S L E C T U R E 4

Chapter 3 Selection Statements

Java Basic Programming Constructs

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

Full file at

Branching and Boolean Expressions

Lab 8: IF statement. Conditionals and Loops. Copyright 2012 Pearson Education, Inc.

Introduction to Java & Fundamental Data Types

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

COMP 202 Java in one week

Programming with Java

Flow Control. Key Notion. Statement Categories. 28-Oct-10

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

CSE 1223: Introduction to Computer Programming in Java Chapter 3 Branching

Using Java Classes Fall 2018 Margaret Reid-Miller

Flow of Control: Loops. Chapter 4

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

Interpreted vs Compiled. Java Compile. Classes, Objects, and Methods. Hello World 10/6/2016. Python Interpreted. Java Compiled

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

CMPT 125: Lecture 4 Conditionals and Loops

Flow Control. Boaz Kantor Introduction to Computer Science, Fall semester IDC Herzliya

Chapter Goals. 3.1 The if Statement. Contents 1/30/2013 DECISIONS

Example: Monte Carlo Simulation 1

Branching and Boolean Expressions

Chapter 4: Conditionals and Loops

Java Flow of Control

Getting started with Java

Objectives. Chapter 4: Control Structures I (Selection) Objectives (cont d.) Control Structures. Control Structures (cont d.) Relational Operators

Section 003 Fall CS 170 Exam 1. Name (print): Instructions:

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

Computer Science & Engineering 150A Problem Solving Using Computers

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

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

Java I/O and Control Structures

CS 101 Fall 2006 Midterm 1 Name: ID:

Chapter 4: Control Structures I (Selection) Objectives. Objectives (cont d.) Control Structures. Control Structures (cont d.

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

COMP 111. Introduction to Computer Science and Object-Oriented Programming

M105: Introduction to Programming with Java Midterm Examination (MTA) Makeup Spring 2013 / 2014

MODULE 02: BASIC COMPUTATION IN JAVA

Selection Statements and operators

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

Introduction to Object-Oriented Programming

DM550 Introduction to Programming part 2. Jan Baumbach.

CSC Java Programming, Fall Java Data Types and Control Constructs

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

QUIZ: What value is stored in a after this

Accelerating Information Technology Innovation

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

What did we talk about last time? Examples switch statements

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

Transcription:

Flow of Control Chapter 3

Outline The if-else Stetement The Type boolean The switch statement

Flow of Control Flow of control is the order in which a program performs actions. Up to this point, the order has been sequential. A branching statement chooses between two or more possible actions. A loop statement repeats an action until a stopping condition occurs.

The if-else Statement A branching statement that chooses between two possible actions. Syntax if (Boolean_Expression) { // do this if Boolean_Expression is true } else { // do this if Boolean_Expression is false }

The if-else Statement Example String message = ""; balance = keyboard.nextdouble(); if (balance >= 0) { balance += (INTEREST_RATE * balance) / 12; message = "Interest has been added "; } else { balance -= OVERDRAWN_PENALTY; message = "Penalties have been deducted "; } System.out.println(message + balance);

The if-else Statement The Action of the if-else Statement

The if-else Statement Download BankBalance.java Sample screen output

Omitting the else Part Sometimes you don't need the else part: int count = 0; if (word.length() > 0) { count++; } System.out.println( count: + count);

Introduction to Boolean Expressions The value of a boolean expression is either true or false. Examples time < limit balance <= 0

Java Comparison Operators Figure 3.4 Java Comparison Operators

Java Logical Operators Figure 3.6

Compound Boolean Expressions Boolean expressions can be combined using the "and" (&&) operator. Example if ((score > 0) && (score <= 100))... The larger expression is true only when both of the smaller expressions are true. Not allowed if (0 < score <= 100)...

Compound Boolean Expressions Boolean expressions can be combined using the "or" ( ) operator. Example if ((quantity > 5) (cost < 10))... Parentheses often are used to enhance readability.

Compound Boolean Expressions When using the larger expression is true When either of the smaller expressions is true When both of the smaller expressions are true. The Java version of "or" is the inclusive or which allows either or both to be true. The exclusive or allows one or the other, but not both to be true.

Negating a Boolean Expression A boolean expression can be negated using the "not" (!) operator. Example (!a b) (a &&!b) (a b) &&!(a && b) // exclusive or

Negating a Boolean Expression Avoiding the Negation Operator

Boolean Operators The Effect of the Boolean Operators && (and), (or), and! (not) on Boolean values

Exercise What is the output of the following code? boolean x=true, y=false, z=true; if ((x && y) (x && z)) { } System.out.println("First condition " + "is true"); if ((y && z)!x) { } System.out.println("Second condition " + "is true");

Using == with ints and chars == is appropriate for determining if two integers or characters have the same value. if (a == 3) where a is an integer type if (firstchar == 'n') where firstchar is a char type

Don t use == with doubles == is not appropriate for determining if two floating points values are equal. Try this in the interactions pane: double d1 = 63.27, d2 = 1.0; d1 + d2 Because of the way floating point values are stored, rounding errors can occur.

Don t use == with doubles Use < and some appropriate tolerance instead. if (Math.abs(b - c) < epsilon) where b, c, and epsilon are floating point types Translation: if the difference between b and c is very small, consider them equal.

Don t use == with object == is not appropriate for determining if two objects have the same value. if (s1 == s2), where s1 and s2 refer to strings, determines only if s1 and s2 refer to a common memory location. If s1 and s2 refer to strings with identical sequences of characters, but stored in different memory locations, (s1 == s2) is false.

Don t use == with object Try it out in the interactions pane: String s1 = "hello"; String s2 = "hello"; System.out.println(s1 == s2); String s3 = "bye"; String s4 = s3; System.out.println(s3 == s4);

equals and equalsignorecase To test the equality of objects of class String, use method equals. s1.equals(s2) or s2.equals(s1) To test for equality ignoring case, use method equalsignorecase. "Hello".equalsIgnoreCase("hello")

Testing Strings for Equality View StringEqualityDemo.java Sample screen output

Summary: equals vs. == == equals int yes no char yes no double no no if (Math.abs(d1 d2) < epsilon) boolean no no if (done) // epsilon is some small number // 0.00000000001 for example if (!done) object no yes if (s1==s2) // compares memory locations if (s1.equals(s2)) // compares contents

Lexicographic Order Lexicographic order is similar to alphabetical order, but is it based on the order of the characters in the Unicode character set. All the digits come before all the letters. All the uppercase letters come before all the lower case letters.

Method compareto Strings consisting of alphabetical characters can be compared using method compareto. if (s1.compareto(s2) < 0) s1 < s2 if (s1.compareto(s2) == 0) s1 and s2 are equal if (s1.compareto(s2) > 0) s1 > s2

Method compareto Try it out in the interactions pane: "alex".compareto("zack") "Book".compareTo("book") "abcdef".compareto("abbdef") "long".compareto("longest")

Nested if-else Statements An if-else statement can contain any sort of statement within it. In particular, it can contain another if-else statement. An if-else may be nested within the "if" part. An if-else may be nested within the "else" part. An if-else may be nested within both parts.

Nested Statements Syntax if (Boolean_Expression_1) { if (Boolean_Expression_2) { Statement(s) } else { Statement(s) } } else { if (Boolean_Expression_3) { Statement(s) } else { Statement(s); } }

Nested Statements Each else is paired with the nearest unmatched if. If used properly, indentation communicates which if goes with which else. Always use curly braces even though they are not required when an if or else block contains only one statement. Indent your code with your IDE to see how the ifs and elses will be paired up.

Multibranch if-else Statements Syntax if (Boolean_Expression_1) { Statement(s) } else if (Boolean_Expression_2) { Statement(s) } else if (Boolean_Expression_3) { Statement(s) } else if } else { Default_Statement(s) }

Multibranch if-else Statements Download and open Grader.java Boolean expressions are evaluated in order The statements in the first branch that evaluate to true are executed no further branches are evaluated Sample screen output

if-else Exercise Rewrite the if-else in Grader.java so that the first if sets grade = 'F' and the last else sets grade = 'A

if-else Exercise if (score < 60) grade = 'F'; else if (score < 70) grade = 'D'; else if (score < 80) grade = 'C'; else if (score < 90) grade = 'B'; else grade = 'A ;

The Conditional Operator if (n1 > n2) else max = n1; max = n2; can be written as max = (n1 > n2)? n1 : n2; The? and : together are call the conditional operator or ternary operator.

The Conditional Operator The conditional operator is useful with print and println statements. System.out.print("You worked " + hours + ((hours > 1)? "hours" : "hour"));

The exit Method Sometimes a situation arises that makes continuing the program pointless. A program can be terminated normally by System.exit(0).

The exit Method Example if (numberofwinners == 0) { } else { } System.out.println ("Error: Dividing by zero."); System.exit (0); oneshare = payoff / numberofwinners; System.out.println("Each winner will receive $" + oneshare);

The Type boolean The type boolean is a primitive type with only two values: true and false. Boolean variables can make programs more readable. if (systemsareok) instead of if((temperature <= 100) && (thrust >= 12000) && (cabinpressure > 30) && )

Boolean Expressions and Variables Variables, constants, and expressions of type boolean all evaluate to either true or false. A boolean variable can be given the value of a boolean expression by using an assignment operator. boolean ispositive = (number > 0);... if (ispositive)...

Naming Boolean Variables Choose names such as ispositive or systemsareok that sound good in an if statement Examples: if (isnoun) if (ispositive) if (systemsareok) if (!done) Avoid names such as numbersign or systemstatus.

Input and Output of Boolean Values Example try it out: boolean boolvar = false; Scanner keyboard = new Scanner(System.in); System.out.println(boolVar); System.out.println("Enter a boolean value:"); boolvar = keyboard.nextboolean(); System.out.println("You entered " + boolvar);

Short-circuit Evaluation Sometimes only part of a boolean expression needs to be evaluated to determine the value of the entire expression. If the first operand associated with an is true, the expression is true. If the first operand associated with an && is false, the expression is false. This is called short-circuit or lazy evaluation.

Short-circuit Evaluation Short-circuit evaluation is not only efficient, sometimes it is essential! A run-time error can result, for example, from an attempt to divide by zero. if ((number!= 0) && (sum/number > 5)) A run-time error can also result from an attempt to call a method on a null object. if ((name!= null) && (name.length() > 0)) Complete evaluation can be achieved by substituting & for && or for.

The switch Statement The switch statement is a mutltiway branch that makes a decision based on an integral (integer or character) expression. Java 7 allows String expressions The action associated with a matching case label is executed. If no match is found, the case labeled default is executed. The default case is optional, but recommended, even if it simply prints a message.

The switch Statement Syntax switch (Controlling_Expression) { case Case_Label: Statement(s); break; case Case_Label: default: }

The switch Statement Download MultipleBirths.java Sample screen output

The switch Statement The action for each case typically ends with the word break. The optional break statement prevents the consideration of other cases. The controlling expression can be anything that evaluates to an integral type (int or char).

switch Exercise Write a program that determines if a word entered by the user starts with a vowel ('a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U'). Use a switch statement.

switch Exercise import java.util.*; public class VowelStuff { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); String word; char firstchar; boolean isvowel; System.out.println("Enter a word:"); word = keyboard.next(); firstchar = word.charat(0); switch (firstchar) { case 'a': case 'A': case 'e': case 'E': case 'i': case 'I': case 'o': case 'O': case 'u': case 'U': isvowel = true; break; } default: isvowel = false; } } if (isvowel) { System.out.println(word + " starts with a vowel"); } else { System.out.println(word + " starts with a consonant"); }

Enumerations Consider a need to restrict contents of a variable to certain values An enumeration lists the values a variable can have Example enum Language {ENGLISH, GERMAN, FRENCH, SPANISH} Language lang; // initially null lang = Language.ENGLISH; System.out.println(lang); // prints ENGLISH;

Enumerations Now possible to use in a switch statement switch (lang) { case GERMAN: System.out.println( Wie geht's? ); break; case FRENCH: System.out.println( Comment vas-tu? ); break; case SPANISH: System.out.println( Cómo estás? ); break; case ENGLISH: default: System.out.println( How are you? ); }