Logic & program control part 2: Simple selection structures

Similar documents
Flow of Control. bool Data Type. Flow Of Control. Expressions. C++ Control Structures < <= > >= ==!= ! &&

Chapter 5. Conditions, Logical Expressions, and Selection Control Structures

Chapter 5 Topics. Chapter 5 Topics. Flow of Control. bool Data Type. Flow of Control. Chapter 5

Conditions and Logical Expressions. C Programming

Programming with Java

Flow of programming execution control is sequential unless a control structure is used to change that there are 2 general types of

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

Flow of Control. Chapter 3. Chapter 3 1

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

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

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Topics. Chapter 5. Equality Operators

Section 2.2 Your First Program in Java: Printing a Line of Text

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

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

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

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

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

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

Course Outline. Introduction to java

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

Boolean Algebra Boolean Algebra

Getting started with Java

Conditionals and Loops

ECE 122 Engineering Problem Solving with Java

Logic & program control part 3: Compound selection structures

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

2.8. Decision Making: Equality and Relational Operators

Computational Expression

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Simple Java Reference

Handout 4 Conditionals. Boolean Expressions.

Mr. Monroe s Guide to Mastering Java Syntax

Introduction to Computer Science Unit 2. Notes

APCS Semester #1 Final Exam Practice Problems

Flow of Control. Chapter 3

Arithmetic and IO. 25 August 2017

Logical Operators and switch

Algorithms and Conditionals

Full file at

Introduction to Java & Fundamental Data Types

when you call the method, you do not have to know exactly what those instructions are, or even how the object is organized internally

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

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

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

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

Control Structures in Java if-else and switch

Control Structures in Java if-else and switch

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

Darrell Bethea May 25, 2011

AP Computer Science A

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Section 2.2 Your First Program in Java: Printing a Line of Text

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Midterm Practice Problems

CS110: PROGRAMMING LANGUAGE I

Chapter 3. Selections

ACS-1903 Basic program structure Feb 16, 2017

Full file at

Introduction to Java Applications

egrapher Language Reference Manual

AP Computer Science Unit 1. Programs

SELECTION. (Chapter 2)

CS 117 Fall Compound boolean expressions. Control Statements, Part 2. Using boolean operators. Boolean operators

What did we talk about last time? Examples switch statements

Boolean Expressions (Conditions)

Object-Oriented Programming

1 Introduction Java, the beginning Java Virtual Machine A First Program BlueJ Raspberry Pi...

CSE 142 Su 04 Computer Programming 1 - Java. Objects

CS111: PROGRAMMING LANGUAGE II

Full file at

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

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

Defining Classes and Methods

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Language Reference Manual

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Università degli Studi di Bologna Facoltà di Ingegneria. Principles, Models, and Applications for Distributed Systems M

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

Java Bytecode (binary file)

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

More non-primitive types Lesson 06

Introduction to Programming Using Java (98-388)

CS111: PROGRAMMING LANGUAGE II

BLOCK STRUCTURE. class block main method block do-while statement block if statement block. if statement block. Block Structure Page 1

STUDENT LESSON A12 Iterations

Chapter 3: Operators, Expressions and Type Conversion

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

MODULE 02: BASIC COMPUTATION IN JAVA

CIS133J. Working with Numbers in Java

Types and Expressions. Chapter 3

Java+- Language Reference Manual

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

CHAPTER 7 OBJECTS AND CLASSES

STUDENT LESSON A7 Simple I/O

AP CS Unit 3: Control Structures Notes

Lecture Set 2: Starting Java

DM503 Programming B. Peter Schneider-Kamp.

Flow of Control. Chapter 3

Transcription:

Logic & program control part 2: Simple selection structures

Summary of logical expressions in Java boolean expression means an expression whose value is true or false An expression is any valid combination of operators and operands Use of parentheses is encouraged; otherwise, use precedence chart to determine order

Logical expressions & program control Relational expressions can be used to control the flow of logic in a program Depending on the truth value of an expression, a program can be made to perform one task or another (but not both) A control structure that fits this description is called a selection structure

Selection & Java In Java, a simple selection structure is created using an if statement, which has the following syntax: if (relational expression) { } statement(s); If only one statement follows the if clause, the curly brackets are unnecessary

Example double otpay = 0.0; // overtime pay time and 1/2 if (hours > 40) { otpay = hours 40; otpay = otpay * wage * 1.5; hours = 40; } pay = otpay + hours * wage;

Potential error condition float average; float total; // average price // sum of prices // entered int howmany; // number of // prices entered... average = total / howmany;

Improved Version float average, // average price total; // sum of prices entered int howmany; // number of prices entered if ( howmany > 0 ) { } average = total / howmany;

After which 2 lines should brackets be added? // 0 if (code == T ) // 1 do 2-7 if this is true System.out.print ( Enter income: ); // 2 income = kb.nextdouble(); // 3 System.out.print ( Enter tax rate: ); // 4 taxrate = kb.nextdouble(); // 5 taxdue = income * taxrate; // 6 System.out.printf( You owe $%.2f, taxdue); // 7

The if-else control structure In the previous examples, a set of statements either executed, or didn t, based on the truth value of an expression In many situations, two options make more sense one set of statements executes if the condition is true, while the other executes if it is false This slightly more complicated version is called an if/else structure

If/else in Java Basic syntax is: if (relational expression) { statement(s); } else { statement(s); }

Example Read an int value from the keyboard If value is less than 0, print its square If value is greater than 0, print its square root

Program logic in Java String s; double value; Scanner kb = new Scanner (System.in); System.out.print( Enter a number: ); s=kb.nextline(); value = Double.parseDouble(s); if (value < 0) System.out.printf( Value squared is %.1f, Math.pow(value, 2.0)); else System.out.printf( Square root of value is %.1f, Math.sqrt(value));

Use of blocks recommended if ( Expression ) { } else { } if clause else clause

What output? and Why? boolean code; code = false; if (! code ) System.out.println( Yesterday ); // A else System.out.println( Tomorrow ); // B

int cardoors, driverage ; double premium, monthlypayment ;... if ( (cardoors == 4 ) && (driverage > 24) ) { System.out.println( LOW RISK ) ; premium = 650.00 ; } else { System.out.println( HIGH RISK ) ; premium = 1200.00 ; } monthlypayment = premium / 12.0 + 5.00 ;

What happens if you omit braces? if ( (cardoors == 4 ) && (driverage > 24) ) System.out.println( LOW RISK ) ; premium = 650.00 ; else System.out.println( HIGH RISK ) ; premium = 1200.00 ; monthlypayment = premium / 12.0 + 5.00 ; COMPILE ERROR OCCURS. The if clause is the single statement following the if.

Adding braces: if ( (cardoors == 4 ) && (driverage > 24) ) { } else System.out.println( LOW RISK ) ; premium = 650.00 ; System.out.println( HIGH RISK ) ; premium = 1200.00 ; monthlypayment = premium / 12.0 + 5.00 ; PROGRAM COMPILES. Is it correct? (T = yes, F = no)

Which is the correct translation of the following? If taxcode is 1, increase price by adding taxrate times price to it. A. if (taxcode = 1) {price += price * taxrate;} B. If (taxcode == 1) price += price * taxrate; C. if (taxcode ==1) price += price * taxrate; D. All are correct

Short-Circuit Benefits one boolean expression can be placed first to guard a potentially unsafe operation in a second boolean expression Time is saved in evaluation of complex expressions using operators and &&

int number ; float x ; Use Precedence Chart if (number!= 0 && x < 1 / number) / has highest priority < next priority!= next priority && next priority What happens if number has value 0?

int float x; Our Example Revisited number; if((number!= 0) && ( x < 1 / number)) is evaluated first and has value false Because operator is &&, the entire expression will have value false. Due to short-circuiting the right side is not evaluated in Java.

Logical expressions & floating-point numbers In general, it isn t a good idea to compare two floating-point numbers for equality This is because floats and doubles always represent approximations of values, and, although 2 equals 2, 2.000000000003 does not equal 2.00000000000019 A better method for comparing floating-point numbers involves deciding how close is close enough to equal

Comparing floating-point numbers for equality The expression below assumes numbers are close enough to equal if they are within 1/100,000,000 of one another: if(math.abs(a-b) < 1.0e-10) else System.out.printf( %f = %f (or close enough)\n, a, b); System.out.printf ( %f and %f are not equal\n, a, b);

Comparing Objects When comparing primitive-type variables, constants, and values, the relational operators are adequate When comparing objects, we can use the relational operators, but they don t mean the same thing they mean with the primitive types

Comparing Objects Recall that, when we declare an object, the identifier in the declaration doesn t contain an object until we initialize it by calling the object s constructor (using the new operator) When we invoke the constructor, a new object is created, and its memory address is associated with the identifier from the declaration

Comparing objects: method equals Because the relational operator == compares only the addresses of objects, many objects have a member method to compare object contents for equality The equals method performs a comparison that depends on its definition within the class For example, for String objects, the equals method performs a letter-by-letter comparison between two Strings, evaluating true if the Strings contents are identical

Example: comparing Strings String s1, s2; s1 = new String ( a string ); s2 = new String ( a string ); The expression s1 == s2 evaluates false The expressions s1.equals(s2) and s2.equals(s1) evaluate true

More String comparison methods The equals method returns true if the calling object and its argument are identical in both spelling and case A second method, equalsignorecase, can be used to compare Strings for spelling only; for example: String s1 = new String ( hello ); String s2 = new String ( HELLO ); s1.equals(s2) returns false s1.equalsignorecase(s2) returns true

More String comparison methods The String class includes two comparison methods besides equals and equalsignorecase: compareto is similar to equals; it is casesensitive comparetoignorecase, as the name implies, ignores case

String compare methods Both compare methods work as follows: if the calling object is less than the argument, the method returns a negative number if the calling object is greater than the argument, the method returns a positive number (greater than 0) if the Strings are equal, the method returns 0 In this context, less than and greater than refer to alphabetical order so, for example, abc is less than bcd because a comes before (is less than) b

String compare methods If the case-sensitive compare method is used, then if two Strings have the same spelling but one contains capital letters, the one with the capital letters will evaluate as less than the one with equivalent lowercase letters So, for example, Hello is less than hello

Exception to the rules One important point about Strings they can sometimes act like primitive objects If a String is instantiated without the new operator, as in the example below: String s1 = no news is good news ; String s2 = no news is good news ; then the expression s1 == s2 evaluates true this is because, if the same String literal is assigned without new to 2 different objects, both objects refer to the same memory location however, if s1 then gets assigned a different String literal, the expression s1 == s2 will be false, because now s2 refers to the original address, but s1 now refers to a new address