27 Pages

14-ch05-3-boolean

Course: ENGLISH engl 500, Spring 2009
School: Washington
Rating:
 
 
 
 
 

Word Count: 1740

Document Preview

Java Building Programs Chapter 5 Lecture 5-3: Boolean Logic reading: 5.2 self-check: #11 - 17 exercises: #12 videos: Ch. 5 #2 Copyright 2009 by Pearson Education Midterm Logistics Bring your UW Student ID card!! Will check your ID while you're leaving Bring your stuff with you while you exit (don't go back to seat) 60 minute exam -10 if you start early or try to write after time Any paper notes allowed,...

Register Now

Unformatted Document Excerpt

Coursehero >> Washington >> Washington >> ENGLISH engl 500

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
Java Building Programs Chapter 5 Lecture 5-3: Boolean Logic reading: 5.2 self-check: #11 - 17 exercises: #12 videos: Ch. 5 #2 Copyright 2009 by Pearson Education Midterm Logistics Bring your UW Student ID card!! Will check your ID while you're leaving Bring your stuff with you while you exit (don't go back to seat) 60 minute exam -10 if you start early or try to write after time Any paper notes allowed, but NO ELECTRONICS Book OK, section handouts OK, past exams + solutions OK, etc. NO CALCULATORS! NO LAPTOPS! Aiming for a median of 80 Will be a curve if the exam is too hard, will not have a hurtful curve if exam is too easy Copyright 2009 by Pearson Education 2 About the Exam 100 pts, 20% of course grade Non-programming 61 pts Expressions (10), parameter mystery (12), if/else simulation (12), while loop simulation (12), assertions (15) Easy Programming 15 pts Medium Programming 15 pts Really Hard Programming 9 pts Topics covered: Chapters 1-5 Topics not covered: see website! Includes Graphics, printf, do/while, break Copyright 2009 by Pearson Education 3 More Exam Info Non-programming questions You do not need to show your work You are not allowed to use calculators (e.g. on expressions) Programming questions Are not graded on style, only external correctness Must write valid Java code that would compile Will not grade comments or pseudo-code Do NOT use abbreviations Do not have to write import statements Write as much as you can: even a method header and the beginnings of a while loop could earn you partial points! Substantial partial credit is given for partially working solutions More info on course website! Copyright 2009 by Pearson Education 4 Logical assertions reading: 5.5 self-checks: #26-28 Copyright 2009 by Pearson Education Logical assertions assertion: A statement that is either true or false. Examples: Java was created in 1995. The sky is purple. 23 is a prime number. 10 is greater than 20. x divided by 2 equals 7. (depends on the value of x) An assertion might be false ("The sky is purple" above), but it is still an assertion because it is a true/false statement. Copyright 2009 by Pearson Education 6 Reasoning about assertions Suppose you have the following code: if (x > 3) { // Point A x--; } else { // Point B x++; } // Point C What do you know about x's value at the three points? Is x > 3? Always? Sometimes? Never? Copyright 2009 by Pearson Education 7 Assertions in code We can make assertions about our code and ask whether they are true at various points in the code. Valid answers are ALWAYS, NEVER, or SOMETIMES. System.out.print("Type a nonnegative number: "); double number = console.nextDouble(); (SOMETIMES) // Point A: is number < 0.0 here? while (number < 0.0) { (ALWAYS) // Point B: is number < 0.0 here? System.out.print("Negative; try again: "); number = console.nextDouble(); // Point C: is number < 0.0 here? } // Point D: is number < 0.0 here? (NEVER) (SOMETIMES) Copyright 2009 by Pearson Education 8 Reasoning about assertions Right after a variable is initialized, its value is known: int x = 3; // is x > 0? ALWAYS In general you know nothing about parameters' values: public static void mystery(int a, int b) { // is a == 10? SOMETIMES But inside an if, while, etc., you may know something: public static void mystery(int a, int b) { if (a < 0) { // is a == 10? NEVER ... } } Copyright 2009 by Pearson Education 9 Assertions and loops At the start of a loop's body, the loop's test must be true: while (y < 10) { // is y < 10? ... } ALWAYS After a loop, the loop's test must be false: while (y < 10) { ... } // is y < 10? NEVER Inside a loop's body, the loop's test may become false: while (y < 10) { y++; // is y < 10? } SOMETIMES Copyright 2009 by Pearson Education 10 "Sometimes" Things that cause a variable's value to be unknown (often leads to "sometimes" answers): reading from a Scanner reading a number from a Random object a parameter's initial value to a method If you can reach a part of the program both with the answer being "yes" and the answer being "no", then the correct answer is "sometimes". If you're unsure, "Sometimes" is a good guess. Often around 1/2 of the correct answers are "sometimes." Copyright 2009 by Pearson Education 11 Assertion example 1 public static void mystery(int x, int y) { int z = 0; // Point A while (x >= y) { // Point B x = x - y; // Point C z++; } // Point D Point A Point B Point C Point D Point E Which of the following assertions are true at which point(s) in the code? Choose ALWAYS, NEVER, or SOMETIMES. x < y SOMETIMES NEVER SOMETIMES SOMETIMES ALWAYS x == y SOMETIMES SOMETIMES SOMETIMES SOMETIMES NEVER z == 0 ALWAYS SOMETIMES SOMETIMES NEVER SOMETIMES } // Point E System.out.println(z); Copyright 2009 by Pearson Education 12 Assertion example 2 public static int mystery(Scanner console) { int prev = 0; int count = 0; int next = console.nextInt(); // Point A while (next != 0) { // Point B if (next == prev) { Which of the following assertions are // Point C true at which point(s) in the code? count++; Choose ALWAYS, NEVER, or SOMETIMES. } prev = next; next = console.nextInt(); next == 0 prev == 0 next == prev // Point D } SOMETIMES Point A SOMETIMES ALWAYS // Point E return count; SOMETIMES SOMETIMES Point B NEVER } NEVER ALWAYS Point C NEVER Point D Point E SOMETIMES ALWAYS NEVER SOMETIMES SOMETIMES SOMETIMES Copyright 2009 by Pearson Education 13 Assertion example 3 // Assumes y >= 0, and returns x^y public static int pow(int x, int y) { int prod = 1; // Point A Which of the following assertions are while (y > 0) { true at which point(s) in the code? // Point B Choose ALWAYS, NEVER, or SOMETIMES. if (y % 2 == 0) { // Point C y > 0 y % 2 == 0 x = x * x; y = y / 2; Point A SOMETIMES SOMETIMES // Point D } else { SOMETIMES Point B ALWAYS // Point E ALWAYS = prod prod * x; Point C ALWAYS y--; SOMETIMES Point D ALWAYS // Point F } NEVER Point E ALWAYS } // Point G Point F SOMETIMES ALWAYS return prod; ALWAYS Point G NEVER } Copyright 2009 by Pearson Education 14 Boolean logic reading: 5.2 self-check: #11 - 17 exercises: #12 Copyright 2009 by Pearson Education Recap: Type boolean boolean: A logical type whose values are true and false. A test in an if, for, or while is a boolean expression. boolean minor = (age < 21); if (minor) { System.out.println("Can't purchase alcohol!"); } boolean expressions can be combined using logical operators: Operator && || ! Description and or Example (2 == 3) && (-1 < 5) (2 == 3) || (-1 < 5) !(2 == 3) Result false true true 16 not Copyright 2009 by Pearson Education De Morgan's Law De Morgan's Law: Rules used to negate or reverse boolean expressions. Useful when you want the opposite of a known boolean test. Original Expression a && b a || b Negated Expression !a || !b !a && !b Alternative !(a && b) !(a || b) Example: Original Code if (x == 7 && y > 3) { ... } Copyright 2009 by Pearson Education Negated Code if (x != 7 || y <= 3) { ... } 17 "Boolean Zen", part 1 Students new to boolean often test if a result is true: if (bothOdd(7, 13) == true) { ... } // bad But this is unnecessary and redundant. Preferred: if (bothOdd(7, 13)) { ... } // good A similar pattern can be used for a false test: if (bothOdd(7, 13) == false) { if (!bothOdd(7, 13)) { Copyright 2009 by Pearson Education // bad // good 18 "Boolean Zen", part 2 Methods that return boolean often have an if/else that returns true or false: 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. Copyright 2009 by Pearson Education 19 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); 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. Copyright 2009 by Pearson Education 20 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); } Copyright 2009 by Pearson Education 21 "Boolean Zen" template Replace public static boolean name(parameters) { if (test) { return true; } else { return false; } } with public static boolean name(parameters) { return test; } Copyright 2009 by Pearson Education 22 When to return? In methods that involve a loop and a boolean return: How do you figure out whether to return true or false? When should the method return its result? Example problem: Write a method seven that accepts a Random parameter and uses it to pick up to 10 lotto numbers between 1 and 30. The method should print each number as it is drawn. Example output from 2 calls: 15 29 18 29 11 3 30 17 19 22 29 5 29 16 4 7 If any of the numbers is a lucky 7, the method should return true. Otherwise, it should return false. Copyright 2009 by Pearson Education 23 Flawed solution Common incorrect solution: // Draws 10 random lotto numbers. // Returns true if one of them is a lucky 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 tries to return immediately after the first roll. This is bad, if that roll isn't a 7; we need to roll all 10 times to see if any of them is a 7. Copyright 2009 by Pearson Education 24 Returning at the right time Corrected code: // Draws 10 random lotto numbers. // Returns true if one of them is a lucky 7. public static boolean seven(Random rand) { for (int i = 1; i <= 10; i++) { int num = rand.nextInt(); System.out.print(num + " "); if (num == 7) { // found lucky 7; can exit now return true; } } } // if we get here, we know there was no 7 return false; Returns immediately if 7 is found, because the answer must be true. If 7 isn't found, we draw the next lotto number. If all 10 aren't 7, the loop ends and we return false. Copyright 2009 by Pearson Education 25 Boolean return questions Write a method named hasAnOddDigit that returns whether any digit of a positive integer is odd. hasAnOddDigit(4822116) returns true hasAnOddDigit(2448) returns false Write a method named allDigitsOdd that returns whether every digit of a positive integer is odd. allDigitsOdd(135319) returns true allDigitsOdd(9175293) returns false Write a method named isAllVowels that returns true if every character in a String is a vowel, else false. isAllVowels("eIeIo") returns true isAllVowels("oink") returns false Copyright 2009 by Pearson Education 26 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) { // check whether last digit is even return false; } n = n / 10; } return true; } 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; } Copyright 2009 by Pearson Education 27
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

Washington - ENGLISH - engl 500
Building Java ProgramsChapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1 self-check: Ch. 4 #2; Ch. 5 # 1-10 exercises: Ch. 4 #2, 4, 5, 8; Ch. 5 # 1-2Copyright 2009 by Pearson EducationA deceptive problem. Write a
Washington - ENGLISH - engl 500
Building Java ProgramsChapter 4 Lecture 4-2: Strings reading: 3.3, 4.3 - 4.4 self-check: Ch. 4 #12, 15 exercises: Ch. 4 #15, 16 videos: Ch. 3 #3Copyright 2009 by Pearson EducationObjects and classes object: An entity that contains: data behavior(var
Washington - ENGLISH - engl 500
Building Java ProgramsChapter 4 Lecture 4-1: if and if/else Statements reading: 4.2self-check: #4-5, 7, 10, 11 exercises: #7 videos: Ch. 4 #2-4Copyright 2009 by Pearson EducationCumulative sum question Write a program that reads two employees' hours
Washington - ENGLISH - engl 500
Washington - ENGLISH - engl 500
Washington - ENGLISH - engl 500
Washington - ENGLISH - engl 500
Washington - ENGLISH - engl 500
Washington - ENGL - engl 500
Nomenclature Worksheet 1: Naming Alkanes and Cycloalkanes23Nomenclature Worksheet 1: Naming Alkanes and Cycloalkanes1. 2. There is only one way to place a double bond and a methyl group on a three carbon chain so the designation that the methyl group i
Washington - ENGL - engl 500
24ChemActivity 6: Alkanes and AlkenesChemActivity 6: Alkanes and Alkenes, Exercises for Part A1.H3C CH3 C HH HH Newman Projection of Eclipsed Conformation2.R2 is neither anti nor gauche to R3R2anti to R3H C H R1H R3gauche to R3R1 is gauche to
Washington - ENGL - engl 500
ChemActivity 5: Resonance17ChemActivity 5: Resonance, Exercises for Part A1. a. Any halogen: e.g. F, Cl, Br, I, etc. b.H H Cl N H H2.HO C O H C C HH C C C H H HO CH CH HO C H C H O C C H H H C C O C C H H H C C H H CO C C C C H O C C C C H H H
Washington - ENGL - engl 500
10ChemActivity 4: Polar Bonds, Polar ReactionsChemActivity 4: Polar Bonds, Polar Reactions, Exercises for Part A1. Ice takes up more space than an equal mass of liquid water. Another way to say this is that ice is less dense than liquid water, and this
Washington - ENGL - engl 500
Which two pairs of letters identify the start and end points of curved arrows giving the likely next step in the mechanism?&quot;bc&quot;b e d f h g c aSummary of Critical Points from Last ClassElectron cloud in Br-Br sloshes back and forth (momentary dipoles)
Washington - ENGL - engl 500
Which two pairs of letters identify the start and end points of curved arrows giving the likely next step in the mechanism?&quot;bc&quot;b e d f h g c a&quot;ha&quot;46%1. 2. 3. 4. 2pts 5. 6. 7.cf &amp; gh cf &amp; hd hc &amp; ba hc &amp; ed ah &amp; cb bf &amp; gh ha &amp; be6. 2pts 7. 4pts 8.
Washington - ENGL - engl 500
Estimate H (in pKa units) for the most likely reaction between each pair (from left to right).H2 C H2C N H2C H C H2180-35 +16O H HCH3 N H-9O H3C HCH3 N H-9H+0HH O H+16H -19H +7H -91. 1pt 2. 2pts 3. 2pts 4. 5. 4pts 6. 1pt 7. 8. 2pts 9.-7
Washington - ENGL - engl 500
Summary of Critical Points from Last ClassCHECKLIST for Drawing a Legitimate Lewis Structure 1. Correct TOTAL number of valence electrons add or take away electrons to account for or + net charge (ion) 2. Sum of the valence electrons around each. H atom
Washington - ENGL - engl 500
What pairs of letters represent the most likely mechanism?b c a d e f h k m n1. 2. 4pts 3. 2pts 4. 5. 1pt 6. 2pts 7. 2pts 8. 9. 0. 10.ad, km ad, ef, km af, km af, mn ak, mn fa, km fa, mk ab, ce, km ag, hk, mn ae, km78%g4%3%4%3%4%2%1%2%0%Sum
Washington - ENGL - engl 500
What is the absolute configuration of each chiral center (from left to right)?180*S*SS, S 2pts 2. S, R 2pts 3. R, S 4. R, R 2pts 5. S, S, R, S 2pts 6. S, S, S, R 1pt 7. S, R, R, S 1pt 8. S, R, S, R 9. R, R, R, S 0. 10. R, R, S, R4pts 1.10%10%10%1
Washington - ENGL - engl 500
Indicate each letter that marks a chiral center. a *b c *d f g * *hmeso compound(chiral centers, but not chiral)* *mk1. 2. 3.1pt 3pts 4pts 2pts 3pts 2ptsa, b, d, f a, d, f, k, m b, c, d, f b, d, f, k, m d, g, h, k, m b, d, g, h, k, m All but a All
Washington - ENGL - engl 500
Which sequence best accomplishes this transformation?3pts1. 2. 3. 4.a) BH3/THF b) H2O2/NaOH/H2O H2O/H2SO4/HgSO4 a) H2/Lindlar catalyst b) BH3/THF c) H2O2/NaOH/H2O d) K2Cr2O7/acid/water a) H2/Ni2B b) H3O+ c) K2Cr2O7/acid/water a) H2/Lindlar catalyst b)
Washington - ENGL - engl 500
Which is a major product of the reaction sequence?OH OH1) BH3, THF 2) H2O2, NaOH(aq) 3) Na2Cr2O7 acid, water1.2pts2.180OOOH3.H 1. 2. 3. O 4. 6. 5. 6. 7. O 9. 8. 9. 10.4.5.HO1 2 3 4 5 6 7 8 9 03ptsOH O O O7.OH H8.O4ptsOOO0.OH H0
Washington - ENGL - engl 500
Announcements Omit the last two reactions shown in CTQ 24, as these pertain to ChemActivity 9B. B2H6 (in Carey) is same as BH3 You are not responsible for Synthetic Transformations 9.2, 9.3, 9.4, &amp; 9.6 Skip any question that requires making or breaking
Washington - ENGL - engl 500
Which two pairs of letters identify the start and end points of curved arrows giving the likely next step in the mechanism?&quot;bc&quot;b e d f h g c a&quot;ha&quot;46%1. 2. 3. 4. 2pts 5. 6. 7.cf &amp; gh cf &amp; hd hc &amp; ba hc &amp; ed ah &amp; cb bf &amp; gh ha &amp; be6. 2pts 7. 4pts 8.
Washington - ENGL - engl 500
Errata Sheet for Organic Chemistry: A Guided Inquiry, 2eStudent Solutions Manual (SSM) changes are marked with a blue SSM answers Errors that are confusing and should definitely be pointed out are shown in red ChemActivity 1 CTQ 18 the &quot;degree&quot; zero's lo
Washington - ENGL - engl 500
Lab #1: Molecular Models The purpose of this lab is to help you visualize the three-dimensional structure of organic molecules using molecular models. You will study conformational analysis and stereochemistry of acyclic alkanes and cyclohexane. Before th
Washington - ENGL - engl 500
DRAFT Syllabus: PHYS 121A, Autumn 2008Lecture Instructor: Prof. Daryl Pedigo email: rdp3@u.washington.edu Office: PAB C138 Phone: (206) 543-4983 Tutorial Instructor: Prof. Peter Shaffer &lt;shaffer@phys.washington.edu&gt; PHYS 121 Lab Instructor: Prof. Jens
Washington - ENGL - engl 500
Organic Chemistry 237A Take Home Exam 1Due at the start of class on Friday 10/24/2008 General Directions (read this page carefully) Submit your group answers via a standard (purple) Scantron bubble sheet ONLY ONE ANSWER SHEET PER GROUP Carefully bubble
FH Accadis - ECON - 101
Using the historical subject of the Salem Witch trials, Arthur Miller's play The Crucible (1953) presents an allegory for events in contemporary America. The Salem Witch Trials took place in Salem, Massachusetts in 1692, and were based on the accusations
FH Accadis - ECON - 101
Vaccinations are useful! Are vaccinations helpful? According to the NY Times Health Guide, vaccinations save millions of children's lives. There are seven childhood vaccines that are recommended by doctors. They include: the Polio vaccine, the varicella v
FH Accadis - ECON - 101
Unit 6 Test Chapters 20-23Student: _1. In arguing for their policies, the new American expansionists of the late 1800s offered all of the following economic and social reasons except A. the United States would soon need to find new sources for the natur
FH Accadis - ECON - 101
Tiresias - A Theban prophet who inhabits the underworld. Tiresias meets Odysseus when Odysseus journeys to the underworld in Book 11. He shows Odysseus how to get back to Ithaca and allows Odysseus to communicate with the other souls in Hades.The blind s
FH Accadis - ECON - 101
The ten spies said that they looked like grasshoppers compared to the people who lived there. I think they were scared and had low self esteem. They did not believe in themselves and their ability to be victorious against the inhabitants of the land. Just
FH Accadis - ECON - 101
United StatesThe United States is bordered by the North American Plate, the Pacific Plate, the Eurasian Plate and the Juan de Fuca Plate. The United States is affected by plate tectonics every day. Plate tectonics is the theory that describes how giganti
FH Accadis - ECON - 101
Textile Fiber Identification Lab Rachel Dennen Emily Schaefer and Stephanie Nguyen Chem 215 Duffey, 5th Hour 2/14/12, 2/15/12, and 2/17/12Hypothesis - I believe that sample #1 was wool, sample #2 was silk, sample #3 was rayon, sample #4 was nylon, sample
FH Accadis - ECON - 101
1 Dennen Rachel Dennen Mrs. Damuth Honors English 10- 3rd Hour 24 September 2011 Anne Bradstreet- &quot;Upon the Burning of our House&quot; Translation Line 19 and 20: Even though he is lacking (something) what he does have for we few left. Line 21 and 22: When I p
FH Accadis - ECON - 101
Rachel Dennen 3-8-10 Hora 6 Artes LingsticasCanciller venezolano: Relacin con Colombia mejorar tras visita de UribeEl presidente de Colombia y lvaro Uribe y el presidente de Venezuela Hugo Chvez. La relacin con Colombia mejorar tras visita de Uribe. Exi
FH Accadis - ECON - 101
Opinin PersonalMi opinin personal de educacin sexual en las escuelas es que necesitamos tener lo en todas las escuelas. Yo creo que necesita ser enseado en las escuelas porque la tasa de natalidad en los Estados Unidos fue 409,840 bebs nacidos por chicas
FH Accadis - ECON - 101
1 Dennen Rachel Dennen Mrs. Damuth Honors English 10- 3rd Hour 12 October 2011 Chapter 15- &quot;Hester and Pearl&quot; 1a. One quotation I had from the book was found on page 161, &quot;Truly do I!&quot; Answered Pearl, looking brightly into her mother's face. 'It is for th
FH Accadis - WORLD - 121
QuickTime and a decompressor are needed to see this picture.QuickTime and a decompressor are needed to see this picture.
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304
Texas Tech - PSY - 3304