Topic 16 boolean logic

Similar documents
Building Java Programs Chapter 5

Type boolean. Building Java Programs. Recap: Type boolean. "Short-circuit" evaluation. De Morgan's Law. Boolean practice questions.

CSc 110, Spring Lecture 13: Random numbers and Boolean Logic. Adapted from slides by Marty Stepp and Stuart Reges

CSc 110, Autumn Lecture 13: Cumulative Sum and Boolean Logic. Adapted from slides by Marty Stepp and Stuart Reges

Lecture 8: The String Class and Boolean Zen

CSc 110, Spring Lecture 14: Booleans and Strings. Adapted from slides by Marty Stepp and Stuart Reges

CSc 110, Autumn Lecture 14: Strings. Adapted from slides by Marty Stepp and Stuart Reges

-Alfred North Whitehead. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from

CS 112 Introduction to Programming

Sierpinski Valentine.

Text processing. Readings: 4.4

Sierpinski Valentine. q Our journey of introducing conditionals

Text processing. Characters. The charat method. Fun with char! char vs. String. Text processing. Readings: 4.4 (pg ) 'h' is a char

Topic 14 while loops and loop patterns

Lecture 4: Conditionals

Topic 11 Scanner object, conditional execution

Topic 11 Scanner object, conditional execution

Building Java Programs

Advanced if/else & Cumulative Sum

Building Java Programs

Building Java Programs

Building Java Programs

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

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

Admin. CS 112 Introduction to Programming. Recap: Exceptions. Summary: for loop. Recap: CaesarFile using Loop. Summary: Flow Control Statements

CS 112 Introduction to Programming

Topic 12 more if/else, cumulative algorithms, printf

CS 112 Introduction to Programming

Flow of Control of Program Statements CS 112 Introduction to Programming. Basic if Conditional Statement Basic Test: Relational Operators

Topic 21 arrays - part 1

Garfield AP CS. User Input, If/Else. Most slides from Building Java Programs. Thanks, Stuart Regesand Marty Stepp!

arrays - part 1 My methods are really methods of working and thinking; this is why they have crept in everywhere anonymously. Emmy Noether, Ph.D.

Topic 22 arrays - part 2. Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from

Menu Driven Systems. While loops, menus and the switch statement. Mairead Meagher Dr. Siobhán Drohan. Produced by:

1. An operation in which an overall value is computed incrementally, often using a loop.

Building Java Programs

Midterm Review Session

Topic 27 classes and objects, state and behavior

Lecture 6: While Loops and the Math Class

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

COMP-202 Unit 4: Programming with Iterations

Topic 12 more if/else, cumulative algorithms, printf

Names and Functions. Chapter 2

Building Java Programs

1 Short Answer (10 Points Each)

Topic 4 Expressions and variables

COE 212 Engineering Programming. Welcome to Exam II Monday May 13, 2013

SSEA Computer Science: Track A. Dr. Cynthia Lee Lecturer in Computer Science Stanford

SSEA Computer Science: Track A. Dr. Cynthia Lee Lecturer in Computer Science Stanford

Topic 13 procedural design and Strings

CMPS 12A Winter 2006 Prof. Scott A. Brandt Final Exam, March 21, Name:

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Some Sample AP Computer Science A Questions - Solutions

CSC 1051 Data Structures and Algorithms I

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

Returns & if/else. Parameters and Objects

Slides adopted from T. Ferguson Spring 2016

CIS October 16, 2018

CSE 142, Autumn 2007 Midterm Exam, Friday, November 2, 2007

CSE 142, Autumn 2008 Midterm Exam, Friday, October 31, 2008

CSE 142/143 Unofficial Commenting Guide Eric Arendt, Alyssa Harding, Melissa Winstanley

CSE 1223: Exam II Autumn 2016

Lecture 19: Recursion

b. Suppose you enter input from the console, when you run the program. What is the output?

Topics. Chapter 5. Equality Operators

Study Guide for Test 2

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

CS 112 Introduction to Programming. Exercise: MatchDB. match1. Removing break. Solution I: Using break. Loop Patterns: break; Fencepost.

Final Examination Semester 2 / Year 2011

Topic 23 arrays - part 3 (tallying, text processing)

CS 106A, Lecture 5 Booleans and Control Flow

Building Java Programs

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

CSE 143 Lecture 10. Recursion

Building Java Programs

NoSuchElementException 5. Name of the Exception that occurs when you try to read past the end of the input data in a file.

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

CSE 142 Sample Midterm Exam #3

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

Warm-Up: COMP Programming with Iterations 1

CSE 142, Spring 2009, Sample Final Exam #2. Good luck!

bool bool - either true or false

CSE 142, Autumn 2010 Midterm Exam, Friday, November 5, 2010

CSE 143 Lecture 11. Decimal Numbers

CSE142 Sample Midterm Spring Name UW NetId (e.g. whitab) Section (e.g., AA) TA

CSC 1051 Data Structures and Algorithms I

Building Java Programs Chapter 4

CIS October 19, 2017

CS 112 Introduction to Programming

CS 112 Introduction to Programming

3.4. FOR-LOOPS 65. for <v a r i a b l e > in < sequence >:

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

Exam 2. Programming I (CPCS 202) Instructor: M. G. Abbas Malik. Total Marks: 40 Obtained Marks:

Lecture 2: Operations and Data Types

Loops and Expression Types

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

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

Introduction to Programming I COS1511 School of Computing Revision Notes

Building Java Programs

COMP-202B - Introduction to Computing I (Winter 2011) - All Sections Example Questions for In-Class Quiz

Transcription:

Topic 16 boolean logic "No matter how correct a mathematical theorem may appear to be, one ought never to be satisfied that there was not something imperfect about it until it also gives the impression of being beautiful." - George Boole Copyright Pearson Education, 2010 Based on slides by Marty Stepp and Stuart Reges from http://www.buildingjavaprograms.com/

Type boolean boolean: A logical type whose values are true and false. A logical <test> is actually a boolean expression. Like other types, it is legal to: create a boolean variable pass a boolean value as a parameter return a boolean value from methods call a method that returns a boolean and use it as a test boolean minor = (age < 21); boolean isprof = name.contains("prof"); boolean lovescs = true; // allow only CSE-loving students over 21 if (minor isprof!lovescs) { System.out.println("Can't enter the club!");

Using boolean Why is type boolean useful? Can capture a complex logical test result and use it later Can write a method that does a complex test and returns it Makes code more readable Can pass around the result of a logical test (as param/return) boolean goodtemp = 40 <= temp && temp <= 90; boolean goodhumidity = 20 <= humidity && humidity <= 70; boolean hastime = time >= 90; // minutes if ((goodtemp && goodhumidity) hastime) { System.out.println("Let's RIDE BIKES!!!!"); else { System.out.println("Maybe tomorrow");

Returning boolean public static boolean isprime(int n) { int factors = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { factors++; // NOTE: GACKY STYLE AHEAD!! GACKY == BAD!! if (factors == 2) { return true; else { return false; Calls to methods returning boolean can be used as tests: if (isprime(57)) {...

Boolean question Improve our "rhyme" / "alliterate" program to use boolean methods to test for rhyming and alliteration. Type two words: Bare blare They rhyme! They alliterate!

Boolean answer if (rhyme(word1, word2)) { System.out.println("They rhyme!"); if (alliterate(word1, word2)) { System.out.println("They alliterate!");... // Returns true if s1 and s2 end with the same two letters. // NOTE: GACKY STYLE AHEAD!! public static boolean rhyme(string s1, String s2) { if (s2.length() >= 2 && s1.endswith(s2.substring(s2.length() - 2))) { return true; else { return false; // Returns true if s1 and s2 start with the same letter. // NOTE: GACKY STYLE AHEAD!! public static boolean alliterate(string s1, String s2) { if (s1.startswith(s2.substring(0, 1))) { return true; else { return false;

"Boolean Zen", part 1 Students new to boolean often test if a result is true: if (isprime(57) == true) { // bad... But this is unnecessary and redundant. Preferred: if (isprime(57)) { // good... A similar pattern can be used for a false test: if (isprime(57) == false) { // bad if (!isprime(57)) { // good

"Boolean Zen", part 2 Programmers often write methods that return boolean often have an if/else that returns true or false: // NOTE: GACKY STYLE AHEAD!! public static boolean bothodd(int n1, int n2) { if (n1 % 2!= 0 && n2 % 2!= 0) { return true; else { return false; But the code above is unnecessarily verbose.

Solution w/ boolean variable We could store the result of the logical test. public static boolean bothodd(int n1, int n2) { boolean test = (n1 % 2!= 0 && n2 % 2!= 0); // NOTE: BAD STYLE AHEAD!! if (test) { // test == true return true; else { // test == false return false; Notice: Whatever test is, we want to return that. If test is true, we want to return true. If test is false, we want to return false.

Solution w/ "Boolean Zen" Observation: The if/else is unnecessary. The variable test stores a boolean value; its value is exactly what you want to return. So return that! public static boolean bothodd(int n1, int n2) { boolean test = (n1 % 2!= 0 && n2 % 2!= 0); return test; An even shorter version: We don't even need the variable test. We can just perform the test and return its result in one step. public static boolean bothodd(int n1, int n2) { return (n1 % 2!= 0 && n2 % 2!= 0);

Replace "Boolean Zen" template public static boolean <name>(<parameters>) { if (<test>) { return true; else { return false; with public static boolean <name>(<parameters>) { return <test>;

Improved isprime method The following version utilizes Boolean Zen: public static boolean isprime(int n) { int factors = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { factors++; return factors == 2; // if n has 2 factors -> true Modify the Rhyme program to use Boolean Zen.

Boolean Zen answer public static void main(string[] args) { Scanner console = new Scanner(System.in); System.out.print("Type two words: "); String word1 = console.next().tolowercase(); String word2 = console.next().tolowercase(); if (rhyme(word1, word2)) { System.out.println("They rhyme!"); if (alliterate(word1, word2)) { System.out.println("They alliterate!"); // Returns true if s1 and s2 end with the same two letters. public static boolean rhyme(string s1, String s2) { return s2.length() >= 2 && s1.endswith(s2.substring(s2.length() - 2)); // Returns true if s1 and s2 start with the same letter. public static boolean alliterate(string s1, String s2) { return s1.startswith(s2.substring(0, 1));

De Morgan's Law De Morgan's Law: Rules used to negate boolean tests.!(a && b) ==!a!b!(a b) ==!a &&!b Useful when you want the opposite of an existing test. Original Expression Negated Expression Alternative a && b!a!b!(a && b) a b!a &&!b!(a b) Example: Original Code if (x == 7 && y > 3) {... Negated Code if (x!= 7 y <= 3) {...

Clicker Question Which of the following is equivalent to the boolean expression?!((x >= y) (z!= x)) A.!(x >= y) &&!(z!= x) B.!(x >= y)!(z!= x) C. (x == y) && (z >= x) D. (x < y) && (z == x) E. More than one of A - D is correct

Boolean practice questions Write a method named isvowel that returns whether a String is a vowel (a, e, i, o, or u), case-insensitively. isvowel("q") returns false isvowel("a") returns true isvowel("e") returns true Write a method isnonvowel that returns whether a String is any character except a vowel. isnonvowel("q") returns true isnonvowel("a") returns false isnonvowel("e") returns false

Boolean practice answers // Enlightened version. I have seen the true way (and false way) public static boolean isvowel(string s) { return s.equalsignorecase("a") s.equalsignorecase("e") s.equalsignorecase("i") s.equalsignorecase("o") s.equalsignorecase("u"); // Enlightened "Boolean Zen" version public static boolean isnonvowel(string s) { return!s.equalsignorecase("a") &&!s.equalsignorecase("e") &&!s.equalsignorecase("i") &&!s.equalsignorecase("o") &&!s.equalsignorecase("u"); // or, return!isvowel(s);

When to return? Methods with loops and return values can be tricky. When and where should the method return its result? Write a method seven that accepts a Random parameter and uses it to draw up to ten lotto numbers from 1-30. If any of the numbers is a lucky 7, the method should stop and return true. If none of the ten are 7 it should return false. The method should print each number as it is drawn. 15 29 18 29 11 3 30 17 19 22 (first call) 29 5 29 4 7 (second call)

Flawed solution // Draws 10 lotto numbers; returns true if one is 7. public static boolean seven(random rand) { for (int i = 1; i <= 10; i++) { int num = rand.nextint(30) + 1; System.out.print(num + " "); if (num == 7) { return true; else { return false; The method always returns immediately after the first roll. This is wrong if that draw isn't a 7; we need to keep drawing.

Returning at the right time // Draws 10 lotto numbers; returns true if one is 7. public static boolean seven(random rand) { for (int i = 1; i <= 10; i++) { int num = rand.nextint(30) + 1; System.out.print(num + " "); if (num == 7) { return true; // found lucky 7; can exit now return false; // if we get here, there was no 7 Returns true immediately if 7 is found. If 7 isn't found, the loop continues drawing lotto numbers. If all ten aren't 7, the loop ends and we return false.

Boolean return questions hasanodddigit : returns true if any digit of an integer is odd. hasanodddigit(4822116) returns true hasanodddigit(2448) returns false alldigitsodd : returns true if every digit of an integer is odd. alldigitsodd(135319) returns true alldigitsodd(9174529) returns false isallvowels : returns true if every char in a String is a vowel. isallvowels("eieio") returns true isallvowels("oink") returns false These problems are available in our Practice-It! system under 5.x.

Boolean return answers public static boolean hasanodddigit(int n) { while (n!= 0) { if (n % 2!= 0) { // check whether last digit is odd return true; n = n / 10; return false; public static boolean alldigitsodd(int n) { while (n!= 0) { if (n % 2 == 0) { return false; n = n / 10; return true; // check whether last digit is even public static boolean isallvowels(string s) { for (int i = 0; i < s.length(); i++) { String letter = s.substring(i, i + 1); if (!isvowel(letter)) { return false; return true;

while loop question Write a method digitsum that accepts an integer parameter and returns the sum of its digits. Assume that the number is non-negative. Example: digitsum(29107) returns 2+9+1+0+7 or 19 Hint: Use the % operator to extract a digit from a number.

while loop answer public static int digitsum(int n) { n = Math.abs(n); // handle negatives int sum = 0; while (n > 0) { // add last digit sum = sum + (n % 10); // remove last digit n = n / 10; return sum;