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

Similar documents
Conditionals and Loops

Comparing Data. Comparing Floating Point Values. Comparing Float Values. CS257 Computer Science I Kevin Sahr, PhD

Conditional Statements

Algorithms and Conditionals

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

Improved algorithm. Java code. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm

Program Development. Chapter 3: Program Statements. Program Statements. Requirements. Java Software Solutions for AP* Computer Science A 2nd Edition

Chapter 3: Program Statements

Control flow, conditionals, boolean expressions, block statements, nested statements. Course website:

Java code. Updated program. Control flow and conditionals CSC 1051 Villanova University. Dr Papalaskari 1. Java Programè Algorithm. Improved algorithm

CS1004: Intro to CS in Java, Spring 2005

Chapter 3. Selections

CMPT 125: Lecture 4 Conditionals and Loops

Java Flow of Control

Chapter 4: Conditionals and Loops

BRANCHING if-else statements

Java I/O and Control Structures

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

Program Development. Java Program Statements. Design. Requirements. Testing. Implementation

Conditional Programming

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

Java I/O and Control Structures Algorithms in everyday life

Topics. Chapter 5. Equality Operators

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

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

Control Structures in Java if-else and switch

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

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.

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

Administration. Conditional Statements. Agenda. Syntax. Flow of control. Lab 2 due now on floppy Lab 3 due tomorrow via FTP

Chapter 4: Conditionals and Loops

Chapter 4. Operations on Data

More Programming Constructs -- Introduction

Flow of Control. Chapter 3

Chapter 4: Conditionals and Loops

Flow of Control. Chapter 3

MEHMET YAYAN - İSMAİL HAKKI ÖZTÜRK CS101/SEC.-2 CLASS NOTES 1. March 28-30, 2007

CS313D: ADVANCED PROGRAMMING LANGUAGE

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Conditionals and Loops Chapter 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

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

Programming in C++ PART 2

Computational Expression

1007 Imperative Programming Part II

Chapter 4: Control Structures I

Handout 4 Conditionals. Boolean Expressions.

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

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

All copyrights reserved - KV NAD, Aluva. Dinesh Kumar Ram PGT(CS) KV NAD Aluva

Logic & program control part 2: Simple selection structures

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

CS 31: Intro to Systems Binary Arithmetic. Martin Gagné Swarthmore College January 24, 2016

Language Fundamentals Summary

Java Review. Java Program Structure // comments about the class public class MyProgram { Variables

Le L c e t c ur u e e 2 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Variables Operators

CMPT 125: Lecture 3 Data and Expressions

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

Conditionals. For exercises 1 to 27, indicate the output that will be produced. Assume the following declarations:

Chapter 3: Decision Structures

Information Science 1

COMP combinational logic 1 Jan. 18, 2016

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Operators in java Operator operands.

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Expressions & Assignment Statements

CT 229 Java Syntax Continued

Chapter 3: Decision Structures

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

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

Bits, Words, and Integers

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

Chapter 3 Selection Statements

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

Chapter 3: Decision Structures

Java enum, casts, and others (Select portions of Chapters 4 & 5)

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

Internet & World Wide Web How to Program, 5/e by Pearson Education, Inc. All Rights Reserved.

Operators. Java operators are classified into three categories:

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

Selection as a Control Structure

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

Control Structures in Java if-else and switch

Chapter 7. Expressions and Assignment Statements ISBN

CS 231 Data Structures and Algorithms, Fall 2016

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

1 Conditions and control statements. 1.1 Conditional statement if

Oct Decision Structures cont d

Decisions (If Statements) And Boolean Expressions

Full file at

Chapter 3: Program Statements

Flow of Control. Chapter 3. Chapter 3 1

WEEK 4 OPERATORS, EXPRESSIONS AND STATEMENTS

Java Primer 1: Types, Classes and Operators

JAVA REVIEW cs2420 Introduction to Algorithms and Data Structures Spring 2015

Chapter 4: Control Structures I (Selection)

Information Science 1

APCS Semester #1 Final Exam Practice Problems

Java Coding 2. Decisions, decisions!

Transcription:

Lab 8: IF statement. Conditionals and Loops

The if condition Statement A conditional statement lets us choose which statement will be executed next if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. if ( condition ) statement; If the condition is true, the statement is executed. If it is false, the statement is skipped.

Logic of an if statement condition evaluated true statement false Can use if to code things like: if total > 100 print $ + total / 100

The if-else Statement if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both

Logic of an if-else statement Can use if to code things like: if total > 100 print $ + total / 100 else print total + cents condition evaluated true statement1 false statement2

Logic of an if-else statement Boolean expression Can use if to code things like: if total > 100 print $ + total / 100 else print total + cents total > 100? true print $ + total / 100 false print total + cents

Boolean Expressions A condition often uses one of Java's equality operators or relational operators, which all return boolean results: == equal to!= not equal to < less than > greater than <= less than or equal to >= greater than or equal to Note the difference between the equality operator (==) and the assignment operator (=)

Logical Operators What if we wanted to test for multiple conditions? For example, what if we want to print the temperature if it s below 80 degrees and greater than 50 degrees? We use logical operators: if (temp < 80 && temp > 50) System.out.println(temp); Created by Emily Hill & Jerry Alan Fails

Logical Operators Boolean expressions can also use the following logical operators:! Logical NOT && Logical AND Logical OR They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands)

Logical NOT The logical NOT operation is also called logical negation or logical complement If some boolean condition a is true, then!a is false; if a is false, then!a is true Logical expressions can be shown using a truth table: a!a true false false true

Logical AND and Logical OR The logical AND expression a && b is true if both a and b are true, and false otherwise The logical OR expression a b is true if a or b or both are true, and false otherwise

Logical AND and Logical OR A truth table shows all possible true-false combinations of the terms Since && and each have two operands, there are four possible combinations of conditions a and b a b a && b a b true true true true true false false true false true false true false false false false

Boolean Expressions Write an expression that evaluates to true if an integer variable age represents the age of a teenager (age >= 13 && age <= 19)

Boolean Expressions Write a statement that prints out It s fun to be a teen if age represents the age of a teenager if (age >= 13 && age <= 19) System.out.println( It s fun to be a teen ); if (age > 12 && age < 20) System.out.println( It s fun to be a teen );

Short-Circuited Operators The processing of && and is short-circuited If the left operand is sufficient to determine the result, the right operand is not evaluated if (count!= 0 && total/count > MAX) System.out.println ("Testing."); This type of processing is commonly used to avoid divide by zero and null pointer exceptions

Quick Check What do the following statements do? if (total!= stock + warehouse) inventoryerror = true; Sets the boolean variable to true if the value of total is not equal to the sum of stock and warehouse if (found!done) System.out.println("Ok"); Prints "Ok" if found is true or done is false

Indentation Indentation is for the human reader, and is ignored by the compiler if (depth >= UPPER_LIMIT) delta = 100; else System.out.println("Reseting Delta"); delta = 0; Despite what the indentation implies, delta will be set to 0 no matter what "Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live." -- Martin Golding

Nested if Statements The statement executed as a result of an if or else clause could be another if statement Braces can be used to specify the if statement to which an else clause belongs An else clause is matched to the last unmatched if (no matter what the indentation implies)

Comparing Data Created by Emily Hill & Jerry Alan Fails

Comparing Float Values You might consider two floating point numbers to be "close enough" even if they aren't exactly equal Don t use == when comparing real numbers (float or double), use a tolerance: if (Math.abs(f1 - f2) < TOLERANCE) System.out.println ("Essentially equal"); The tolerance could be set to any appropriate level, such as 0.000001 or even 0.01, depending on precision

Comparing Characters Characters can be compared like numbers, since internally they are encoded as numbers: For example: a + 1 => b A + 1 => B a == a => true Characters Unicode Values 0 9 48 through 57 A Z 65 through 90 a z 97 through 122

Comparing Strings Remember a String is an object in Java, so we cannot use relational operators (==, <, >, etc.) to compare strings (or objects) Instead, use the equals method: if (name1.equals(name2)) System.out.println ("Same name"); Or compareto. For example, a call to name1.compareto(name2) returns zero if name1 and name2 are equal (contain the same characters) returns a negative value if name1 is less than name2 returns a positive value if name1 is greater than name2

Comparing Objects When applied to objects, == returns true if the two references are aliases of each other The equals method is defined for all objects, but unless we redefine it when we write a class, it has the same semantics as the == operator It has been redefined in the String class to compare the characters in the two strings When you write a class, you can redefine the equals method to return true under whatever conditions are appropriate

Practice! Created by Emily Hill & Jerry Alan Fails

Part A: static methods tested in main Write a method that takes someone s age as input and returns true if they can vote but not drink beer. (Note that you must be 18 to vote and 21 to drink.) Test in main Write a method isvowel that takes a character as input and returns whether or not the letter is a vowel. Test in main Write a method isvowel like above but taking a String as input instead of a character. Test in main Created by Emily Hill & Jerry Alan Fails

Part B: Timer class Create a Timer class that counts down from n to 0 (where n is specified by the constructor, 5 by default for the default constructor) You will need 2 fields: n & time_left Write a tick method that decrements the time left if time left is greater than zero, otherwise it prints: You have no time left! Created by Emily Hill & Jerry Alan Fails

Homework Finish this lab Work on CodingBat Read Chapter 5 Created by Emily Hill & Jerry Alan Fails