Decisions (If Statements) And Boolean Expressions

Similar documents
First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

First Programs. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Common Mistakes with Functions. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

Methods (Functions) CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington

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

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

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

Chapter 3. Selections

Term 1 Unit 1 Week 1 Worksheet: Output Solution

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

Topics. Chapter 5. Equality Operators

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

Flow of Control. Chapter 3

Flow of Control. Chapter 3

AP COMPUTER SCIENCE A

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

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

AP CS Unit 3: Control Structures Notes

STUDENT LESSON A12 Iterations

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

JAVA OPERATORS GENERAL

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

Oct Decision Structures cont d

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

Selection statements. CSE 1310 Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington

Java Coding 2. Decisions, decisions!

2.8. Decision Making: Equality and Relational Operators

Introduction to Computer Science Unit 2. Notes

Arrays and Array Lists. CSE 1310 Introduction to Computers and Programming Vassilis Athitsos and Alexandra Stefan University of Texas at Arlington

Arithmetic and IO. 25 August 2017

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

Selections. CSE 114, Computer Science 1 Stony Brook University

Mr. Monroe s Guide to Mastering Java Syntax

Loops (while and for)

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

CONDITIONAL EXECUTION

Java Programming Fundamentals - Day Instructor: Jason Yoon Website:

COMPUTER APPLICATIONS

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

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

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

Computational Expression

Java Simple Data Types

DM503 Programming B. Peter Schneider-Kamp.

Question: Total Points: Score:

Conditional Programming

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

What did we talk about last time? Examples switch statements

COSC 123 Computer Creativity. Java Decisions and Loops. Dr. Ramon Lawrence University of British Columbia Okanagan

IEEE Floating-Point Representation 1

Introduction to Java Applications

BlueJ Demo. Topic 1: Basic Java. 1. Sequencing. Features of Structured Programming Languages

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

Question: Total Points: Score:

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

Fall CS 101: Test 2 Name UVA ID. Grading. Page 1 / 4. Page3 / 20. Page 4 / 13. Page 5 / 10. Page 6 / 26. Page 7 / 17.

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

Midterm Examination (MTA)

Java Simple Data Types

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

APCS Semester #1 Final Exam Practice Problems

COMP 110 Project 1 Programming Project Warm-Up Exercise

Key Java Simple Data Types

1 Short Answer (15 Points Each)

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

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Controls Structure for Repetition

Chapter 3 Selection Statements

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

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 24, Name: KEY 1

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

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

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

H212 Introduction to Software Systems Honors

Introduction to Computer Science Unit 2. Notes

Chapter 13 Control Structures

download instant at

CSE 114 Computer Science I

Motivations. Chapter 3: Selections and Conditionals. Relational Operators 8/31/18. Objectives. Problem: A Simple Math Learning Tool

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Software Practice 1 - Basic Grammar Basic Syntax Data Type Loop Control Making Decision

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

CS 302: Introduction to Programming

Selection Control Structure CSC128: FUNDAMENTALS OF COMPUTER PROBLEM SOLVING

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.

Java Programming Language. 0 A history

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

Text Input and Conditionals

Loops. CSE 114, Computer Science 1 Stony Brook University

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

Date: Dr. Essam Halim

Place your name tag here

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions

Lectures 3-1, 3-2. Control Structures. Control Structures, Shimon Schocken IDC Herzliya, slide 1

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

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

2.2 - Making Decisions

Example: Monte Carlo Simulation 1

Transcription:

Decisions (If Statements) And Boolean Expressions CSE 1310 Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington Last updated: 2/15/16 1

Syntax if (boolean_expr) if-line 1; if-line 2; if-line m; else else-line 1; else-line 2; else-line n; It is a compound statement : a statement that includes multiple statements. Flow-chart last instruction before if True if-line 1 if-line 2... if-line m Cond? False 1 st instruction after if else-line 1 else-line 2... else-line n 2

Summary if-else if (condition) else if with no else if (condition) Multiple choices (e.g. for menus): (There is also a dedicated instruction for this: switch). if (condition 1) else if (condition 2) else if (condition 3). else if (condition n) else //with or without this else 3

Example 1 import java.util.scanner; public class example1 public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.printf("How old are you? "); int age = in.nextint(); if (age < 21) System.out.printf("How about some milk?\n"); else System.out.printf("How about some beer?\n"); System.out.printf("Bye\n"); Example Output 1: How old are you? 18 Example Output 2: How old are you? 21 Example Output 3: How old are you? 24 4

Example 1 import java.util.scanner; public class example1 public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.printf("How old are you? "); int age = in.nextint(); if (age < 21) System.out.printf("How about some milk?\n"); else System.out.printf("How about some beer?\n"); System.out.printf("Bye\n"); Example Output 1: How old are you? 18 How about some milk? Bye Example Output 2: How old are you? 21 How about some beer? Bye Example Output 3: How old are you? 24 How about some beer? Bye 5

Example 2: no else import java.util.scanner; public class example1 public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.printf("How old are you? "); int age = in.nextint(); Example Output 1: How old are you? 29 if (age <= 18) System.out.printf("You are a teenager.\n"); System.out.printf("You are young.\n"); System.out.printf("Bye.\n"); Example Output 2: How old are you? 15 Note: the else part of an if statement IS OPTIONAL. No else in this example. 6

Example 2: no else import java.util.scanner; public class example1 public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.printf("How old are you? "); int age = in.nextint(); Example Output 1: How old are you? 29 Example Output 2: How old are you? 15 if (age <= 18) System.out.printf("You are a teenager.\n"); System.out.printf("You are young.\n"); True 18? False teenager System.out.printf("Bye\n"); young Note: the else part of an if statement IS OPTIONAL. No else in this example. 7

Example 2: no else import java.util.scanner; public class example1 public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.printf("How old are you? "); int age = in.nextint(); if (age <= 18) System.out.printf("You are a teenager.\n"); System.out.printf("You are young.\n"); System.out.printf("Bye\n"); Example Output 1: How old are you? 29 Bye Example Output 2: How old are you? 15 You are a teenager. You are young. Bye True teenager young 18? False Note: the else part of an if statement IS OPTIONAL. No else in this example. 8

See example Nested if statements 9

Combining if statements: 4 ways Sequential Nested Multiple choice A combination of the above 10

Sequential if-statements if (condition 1) // block A else // block B True block A C1? False block B if (condition 2) // block C else // block D True block C C2? False block D if (condition 3) // block E else // block F True block E C3? False block F 11

12

Multiple Cases / Multiple Choice Draw the flow chart! if (condition 1) // block A else if (condition 2) // block B else if (condition 3) // block C else //with or without this else // block D E.g.: print category by age: age < 18: not an adult 18 age < 40: young adult 40 age < 60: middle-aged 60 age : senior citizen 13

Multiple Cases / Multiple Choice if (condition 1) // block A else if (condition 2) // block B else if (condition 3) // block C else //with or without this else // block D instructions block A True C1? True instructions block B False C2? True instructions block C False C3? False instructions block D Important: - If C1 is True, C2 will NOT even be evaluated! - The else binds them together. DO not skip it! Flow chart How many different paths of execution are possible here? 14

Multiple Cases Error: missing else Draw the flow chart! if (condition 1) // block A if (condition 2) // no else // block B if (condition 3) // no else // block C else //with or without this else // block D

Multiple Cases Error: missing else True C1? False if (condition 1) // block A if (condition 2) // no else // block B if (condition 3) // no else // block C else //with or without this else // block D block A True block B True C2? C3? False False block C block D

Checking Multiple Cases public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.printf("How old are you? "); int age = in.nextint(); if (age < 18) System.out.printf("You are not an adult.\n"); else if (age < 40) System.out.printf("You are a young adult.\n"); else if (age < 60) else System.out.printf("You are middle aged.\n"); System.out.printf("You are a senior citizen.\n"); Example Output 1: How old are you? 18 Example Output 2: How old are you? 45 Example Output 3: How old are you? 65 17

Checking Multiple Cases public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.printf("How old are you? "); int age = in.nextint(); if (age < 18) System.out.printf("You are not an adult.\n"); else if (age < 40) System.out.printf("You are a young adult.\n"); else if (age < 60) else System.out.printf("You are middle aged.\n"); System.out.printf("You are a senior citizen.\n"); Example Output 1: How old are you? 18 You are a young adult. Example Output 2: How old are you? 45 You are middle aged. Example Output 3: How old are you? 65 You are a senior citizen. 18

import java.util.scanner; public class example1 (Multiple cases bug:) Successive ifs, vs. if-else if public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.printf("How old are you? "); int age = in.nextint(); How will the program behavior change if we remove the else that is highlighted in red? Consider an age of 30. if (age < 40) System.out.printf("You are young.\n"); else if (age < 60) else System.out.printf("You are middle aged.\n"); System.out.printf("You are old.\n"); Output with else if How old are you? 30 Output with two successive if statements: How old are you? 30 19

import java.util.scanner; public class example1 (Multiple cases bug:) Successive ifs, vs. if-else if public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.printf("How old are you? "); int age = in.nextint(); This is an example where using successive if statements, instead of an else if, leads to incorrect behavior. if (age < 40) System.out.printf("You are young.\n"); else if (age < 60) else System.out.printf("You are middle aged.\n"); System.out.printf("You are old.\n"); Output with else if How old are you? 30 You are young. Output with two successive if statements: How old are you? 30 You are young. You are middle aged. 20

Placement of Braces public class example1 public static void main(string[] args) int a = 7; if (a > 5) System.out.printf("a > 5.\n"); First way: placed under if public class example1 public static void main(string[] args) int a = 7; if (a > 5) System.out.printf("a > 5.\n"); Second way: placed at the end of the if line. This is also fine, if you want to do it that way. 21

Braces on NetBeans Source->Format will automatically set the position of braces for you. Again, this will work only if your code is valid Java code, that can run. EXTRA: You can set some preferences for automatic formatting using Tools->Options. Select Editor at the top. Select Formatting. In "Category" select braces. You can specify if you want braces on their own in a new line, or at the end of the current line. 22

Not Using Braces public class example1 public static void main(string[] args) int a = 7; if (a > 5) System.out.printf("a > 5.\n"); These two examples do not use braces under if. This is legal, but it can lead to bugs when you add more lines. public class example1 public static void main(string[] args) int a = 7; if (a > 5) System.out.printf("a > 5.\n"); ***NOT*** RECOMMENDED 23

Not Using Braces - Example of Bug public class example1 public static void main(string[] args) int a = 3; if (a > 5) System.out.printf("a = %d.\n", a); System.out.printf("a > 5.\n"); Not using braces under if: it is legal, but it can lead to bugs when you add more lines. What will this example print? How many if-lines are there? 24

Not Using Braces - Example of Bug public class example1 public static void main(string[] args) int a = 3; if (a > 5) System.out.printf("a = %d.\n", a); System.out.printf("a > 5.\n"); Not using braces under if: it is legal, but it can lead to bugs when you add more lines. public class example1 public static void main(string[] args) int a = 3; if (a > 5) System.out.printf("a = %d.\n", a); System.out.printf("a > 5.\n"); What will this example print? a > 5 How many if-lines are there? Just one (if you do not use braces under if, there can only be one if-line). The top example does the same thing as the bottom example. 25

Not Using Braces - Example of Bug public class example1 public static void main(string[] args) int a = 3; if (a > 5) System.out.printf("a = %d.\n", a); System.out.printf("a > 5.\n"); public class example1 public static void main(string[] args) int a = 3; if (a > 5) System.out.printf("a = %d.\n", a); System.out.printf("a > 5.\n"); If you wanted two if-lines, you should have used braces, as shown on the bottom example on this slide. 26

Common Bug: semicolon public class example1 public static void main(string[] args) int a = 3; if (a > 5); System.out.printf("a = %d.\n", a); System.out.printf("a > 5.\n"); Run it. What will it print? 27

Common Bug: semicolon public class example1 public static void main(string[] args) int a = 3; if (a > 5); System.out.printf("a = %d.\n", a); System.out.printf("a > 5.\n"); It will print: a = 3. a > 5. What is the problem? What did you expect it to print? Nothing since (a>5) is false. 28

Common Bug: semicolon public class example1 public static void main(string[] args) int a = 3; if (a > 5); System.out.printf("a = %d.\n", a); System.out.printf("a > 5.\n"); It will print: a = 3. a > 5. What is the problem? Semicolon on the if line. public class example1 public static void main(string[] args) int a = 3; if (a > 5) System.out.printf("a = %d.\n", a); System.out.printf("a > 5.\n"); fixed. 29

The Importance of Indentation import java.util.scanner; public class example1 public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.printf("How old are you? "); int age = in.nextint(); if (age < 40) System.out.printf("You are young.\n"); else if (age < 60) else System.out.printf("You are middle aged.\n"); System.out.printf("You are old.\n"); This program is indented appropriately. Every time we open a brace, we increase indentation. Every time we close a brace, we decrease indentation. Netbeans does this for you automatically, but may get confused every now and then, and then you need to fix the indentations manually. 30

The Importance of Indentation import java.util.scanner; public class example1 public static void main(string[] args) Scanner in = new Scanner(System.in); if (age < 40) System.out.printf("How old are you? "); int age = in.nextint(); System.out.printf("You are young.\n"); if (age < 60) System.out.printf("You are middle aged.\n"); else System.out.printf("You are old.\n"); This program is indented inappropriately. Indentation does not change program behavior, but makes program harder to read, and mistakes harder to find. 31

Indentation on NetBeans NetBeans can automatically indent your code. Select Source->Format. This will work only if your code is valid Java code. If your code cannot run because of syntax errors, NetBeans may get confused about the correct indentation. 32

Conditionals with Strings: An Example Write a program that: Asks the user to enter the name of the month. Prints "M has X days" where M is the month and X is the correct number of days. If the user did not enter a valid month name, the program prints "M is not a valid month" 33

import java.util.scanner; Conditionals with Strings: An Example public class example1 public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.printf("Enter the name of a month: "); String m = in.next(); if ((m.equals("january")) (m.equals("march")) (m.equals("may")) (m.equals("july")) (m.equals("august")) (m.equals("october")) (m.equals("december"))) System.out.printf("%s has 31 days.\n", m); else if ((m.equals("april")) (m.equals("june")) (m.equals("september")) (m.equals("november"))) System.out.printf("%s has 30 days.\n", m); else if (m.equals("february")) System.out.printf("%s has 28 or 29 days.\n", m); else System.out.printf("%s is not a valid month.\n", m); 34

The String indexof Method Suppose that variables str1 and str2 are strings. Suppose you want to see if str1 contains str2. You can call str1.indexof(str2). If str1 contains str2, indexof returns the FIRST position where str2 appears in str1. If str1 does NOT contain str2, indexof returns -1. 35

indexof Example Write a program that: Asks the user to enter a single letter. If the user enters a string with more than one letter, exit the program. If the letter is a vowel, print that it is a vowel Else, print that the letter is not a vowel. 36

import java.util.scanner; indexof Example public class example1 public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.printf("Enter a single letter: "); String c = in.next(); if (c.length()!= 1) System.out.printf("invalid input.\n"); System.exit(0); String vowels = "aeiouaeiou"; int result = vowels.indexof(c); if (result!= -1) System.out.printf("%s is a vowel.\n", c); else System.out.printf("%s is not a vowel.\n", c); 37

import java.util.scanner; indexof public class example1 public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.printf("Enter a single letter: "); Example Note: if we want the program to finish, we write: System.exit(0); String c = in.next(); if (c.length()!= 1) System.out.printf("invalid input.\n"); System.exit(0); String vowels = "aeiouaeiou"; int result = vowels.indexof(c); if (result!= -1) else System.out.printf("%s is a vowel.\n", c); System.out.printf("%s is not a vowel.\n", c); 38

import java.util.scanner; Version public class example1 public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.printf("Enter a single letter: "); without indexof Doable, but painful. Would be even more painful if you were checking consonants instead of vowels. String c = in.next(); if (c.length()!= 1) System.out.printf("invalid input.\n"); System.exit(0); if (c.equals("a") c.equals("e") c.equals("i") c.equals("o") c.equals("u") else c.equals("a") c.equals("e") c.equals("i") c.equals("o") c.equals("u")) System.out.printf("%s is a vowel.\n", c); System.out.printf("%s is not a vowel.\n", c); 39

Boolean Variables and Expressions Comparing Strings 40

The boolean Type Answers to questions are data of type boolean. Data of type boolean can only have two values: true, or false. true and false are reserved keywords in Java. public class example1 public static void main(string[] args) double a = 3.2; double b = 4.0; boolean v1 = (a < 4.3); System.out.printf("v1 = %b\n", v1); Output: v1 = true v2 = false v3 = true boolean v2 = (a == b); System.out.printf("v2 = %b\n", v2); boolean v3 = (a!= b); System.out.printf("v3 = %b\n", v3); 41

Comparisons of Numbers The following operators compare numerical values (of type double or int), and generate boolean results: Operator Meaning Operator Meaning == equals!= not equal to > greater than >= greater than or equal to < less than <= less than or equal to public class example1 public static void main(string[] args) double a = 3.2; double b = 4.0; System.out.printf("a = %.1f, b = %.1f\n", a, b); System.out.printf("a == b: %b\n", a == b); System.out.printf("a!= b: %b\n", a!= b); System.out.printf("a > b: %b\n", a > b); System.out.printf("a >= b: %b\n", a >= b); System.out.printf("a < b: %b\n", a < b); System.out.printf("a <= b: %b\n", a <= b); Output: a = 3.2, b = 4.0 a == b: false a!= b: true a > b: false a >= b: false a < b: true a <= b: true 42

Using Parentheses When you assign a boolean variable, use parentheses to make it easy to read your code. Even if your code runs correctly without parentheses, parentheses are still recommended to make sure you don't get confused. Example: setting c equal to the value of "a equals b". public class example1 public static void main(string[] args) double a = 3.2; double b = 4.0; boolean c = a == b; boolean d = (a == b); Correct, but confusing (not recommended!) Preferred style (parenthesize) What is the value of c in this example? What is the value of d in this example? They are both equal to false 3.2 is NOT equal to 4.0. 43

Comparing Numbers: Examples Four ways of doing the same comparison (3.2 < 4.0) And combining operators: v5 = (a < 4.3-2.6); public class example1 public static void main(string[] args) double a = 3.2; double b = 4.0; Output: boolean v1 = (a < b); //first way System.out.printf("v1 = %b\n", v1); boolean v2 = (a < 4.0); //second way boolean v3 = (3.2 < 4.0); // 3-rd way // 4-th way. Note that v4 does not exist. System.out.printf("v4 = %b\n", 3.2 < 4.0); boolean v5 = (a < 4.3-2.6); System.out.printf("v5 = %b\n", v5); v1 = true v4 = true v5 = false 44

Comparing Numbers common error = / == public class example1 public static void main(string[] args) double a = 3.2; double b = 4.0; //boolean v1 = (a = 3.2); boolean v1 = (a == 3.2); System.out.printf("v1 = %b\n", v1); Output: Error (does not run, we need == sign instead of = sign. Very common error!!! 45

Comparing doubles for equality public class example1 public static void main(string[] args) double x = 2; double y = Math.sqrt(2); if ((y*y) == 2) System.out.println("equal"); else System.out.println("not equal"); Output: not equal Reason: y*y is not exactly 2!!! Solution: Replace: (y*y) == 2 with: Math.abs((y*y)-2)<0.0000001 46

Truth Tables for:, &&,! The following logical operators can be used to ask more complex questions. They produce boolean results : Syntax Meaning a b a OR b One is sufficient: If the answer to either a or to b is yes/true. Also ok if they are both true. a && b a AND b I want both a and b : I want the answer to both questions to be yes/true.!a NOT a Take the answer for a and flip it! (Like kids do.) OR AND a b a b a && b true true true false false true false false NOT a!a true false 47

Truth Tables for:, &&,! The following logical operators can be used to ask more complex questions. They produce boolean results : Syntax Meaning a b a OR b One is sufficient: If the answer to either a or to b is yes/true. Also ok if they are both true. a && b a AND b I want both a and b : I want the answer to both questions to be yes/true.!a NOT a Take the answer for a and flip it! (Like kids do.) OR AND a b a b a && b true true true true true false true false false true true false false false false false NOT a!a true false false true 48

Boolean Expressions Worksheet OR AND NOT a b a b a && b a!a true true true true true false true false false true true false false false false false true false false true // What will the following instructions print? int x = 3; int y = 5; System.out.println("B1: " + ((x == 3) && (y < 10)) ); System.out.println("B2: " + ((x == 3) && (y > 10)) ); System.out.println("B3: " + ((x == 3) (y < 10)) ); System.out.println("B4: " + ((x == 3) (y > 10)) ); System.out.println("B5: " +!(x == 3) ); System.out.println("B6: " +!(x == 4) ); System.out.println("B7: " + ((x == y) && (x + y == 8)) ); System.out.println("B8: " + ((x == y) (x + y == 8)) ); 49

Complicated Use of Operators What does this code print? System.out.println( (3 == 5) && (2 < 3) (3 >= 0) ); Use parentheses to make the meaning clear. ((3 == 5) && (2 < 3)) (3 >= 0) (3 == 5) && ((2 < 3) (3 >= 0)) 50

Complicated Use of Operators What does this code print? System.out.println( (3 == 5) && (2 < 3) (3 >= 0) ); Use parentheses to make the meaning clear. ((3 == 5) && (2 < 3)) (3 >= 0) true (3 == 5) && ((2 < 3) (3 >= 0)) false 51

And just when you thought you got it // What will these lines print? // Exceptional case where the == works. DO NOT DO THIS. String s1 = "Rob"; System.out.println("Ex.B1: ", s1 == "Rob" ); // For all other cases it does not work: String s2 = "Robert"; String s3 = s2.substring(0, 3); System.out.println("Ex.A1: ", s3 == "Rob" ); // Correct string comparison: System.out.println("Ex.A2: ", s1.equals("rob") ); System.out.println("Ex.B2 ", s3.equals("rob") ); 52

Comparisons of Strings Syntax Meaning s1.equals(s2) s1 equals s2 s1.compareto(s2) < 0 s1 comes before s2 in Java's version of alphabetical order s1.compareto(s2) == 0 s1 equals s2 s1.compareto(s2) > 0 s1 comes after s2 in Java's version of alphabetical order Hint to remember compareto behavior: think of it as computing s1-s2 53

Character ordering 0 < 1 < < 9 < A < B <. < Z < a < b < z Each character has a code. This code is used to: Store/represent the character (in binary) Compare characters (based on the value of the code) Encoding The mapping between characters and codes There are several encodings: ASCII (old) UTF-8 (popular) https://en.wikipedia.org/wiki/utf-8 https://en.wikipedia.org/wiki/ascii 54

String Comparison Worksheet // What will these lines print? // Discuss WHAT EACH PIECE OF CODE DOES: "6a: " + ("h".compareto("h") < 0) System.out.println("1 : " + "hello".equals("hello") ); System.out.println("2 : " + "hello".equals("hello") ); System.out.println("3a: " + "hello".compareto("hello") ); System.out.println("3c: " + "world".compareto("hello") ); System.out.println("3b: " + "hello".compareto("world") ); System.out.println("4a: " + "h".compareto("w") ); System.out.println("4b: " + "h".compareto("world") ); System.out.println("4c: " + "hello".compareto("world") ); // Add code below so that it prints true for all (e.g. 5a: true ) System.out.println("5a: " + "hello".compareto("hello") ); System.out.println("5b: " + "world".compareto("hello") ); // What will these lines print? System.out.println("6a: " + ("h".compareto("h") < 0) ); System.out.println("6b: " + ("h".compareto("w") < 0) ); System.out.println("6c: " + ("hello".compareto("world") < 0) ); System.out.println("7 : " + ("act".compareto("actor") < 0) ); System.out.println("8 : " + ("97".compareTo("145") < 0) ); 55

Modulo operator: % % computes the remainder of division. Returns an int. a%b gives what remains from a after removing as many of b as possible. a%b is a, whenever a<b (I cannot fit b in a at all, therefore all of a is the remainder.) Example: 5%7 is 5 Expression Result 7%5 2 5%7 5 39 % 12 3 100%25 0 125%25 0 Typical Usage Identify odd/even Example applications No TV on even days. Identify white squares on a chess board. Identify every b-th event Every b days I run my Sprinklers. Use (day%b == 0) Produce patterns (using loops) Produce: **-**-**-** (user chooses length) Produce a chess board of size n 56

More Examples of Conditionals Determining if integer K is a divisor of integer N. Determining if a day is a weekend. Determining if a day is a weekday or a weekend. Determining if a month is a summer month. Determining the season of a month. Determining if a year is a leap year. Calculating tax. Translating English to Spanish. More accurately: translating a few English words to Spanish. Determining the weekday for a date in February 2015. 57

Example 2: no else import java.util.scanner; program flowchart public class example1 public static void main(string[] args) Scanner in = new Scanner(System.in); System.out.printf("How old are you? "); int age = in.nextint(); Create Scanner object kb Print: how old are you? age <- user (kb) if (age <= 18) True 18? False System.out.printf("You are a teenager.\n"); System.out.printf("You are young.\n"); print teenager System.out.printf("Bye\n"); Print young Print Bye Note: the else part of an if statement IS OPTIONAL. No else in this example. 58