Lab 6 Wrong public static void set Color

Lab 6 // Wrong public static void set. Color. Big. Square(Graphics g, int x, int y) { if (x >= 2) if (x < 8) if (y >= 2) if (y < 8) g. set. Color(Color. green); The else goes with the most local (closest) if. else The compiler compiles the if statements one at g. set. Color(Color. yellow); a time. When it gets to the last if, it associates the next else with it. // Right (Another way to do it. ) public static void set. Color. Big. Square(Graphics g, int x, int y) { g. set. Color(Color. yellow); if (x >= 2) if (x < 8) if (y >= 2) if (y < 8) g. set. Color(Color. green); For what values of x and y do we } execute this statement?


Boolean logic reading: 5. 3 3

boolean type • boolean is a primitive type to represent logical values. • Logical values are true and false. • A boolean expression produces either true or false, e. g. a < b, c == d, f <= g (a, b, c, d, e, f, g all declared a primitive type, char, int, double, etc. ). • The <condition> in if statements, while and for loops is boolean. E. g. for (int i = 1; i <= n; i++)…, while ( height > limit ), if (a<b) … • Examples of boolean variables: boolean minor = (age < 21); boolean pass = (total >= 60); boolean taking. COS 160 = true; if (minor) { System. out. println("Can't purchase alcohol!"); } Note: Using the test if ( minor == true ) is redundant. If minor is true then minor == true is true. Also if minor is false then minor == true is false. • You can create boolean variables, pass boolean parameters, return boolean values from methods, call a method that returns a boolean and use it in a test. 4

Using boolean • Why is type boolean useful? – – – Can record whether something has or has not occurred. Can capture a complex logical test result and use it later Can write a method that does a complex test and returns true or false Makes code more readable Can pass around the result of a logical test (as param/return) 5

Some loops are terminated by testing if something has happened. boolean done = false; while (!done) { // whatever // at some point, when the event occurs, set done = true; } 6

• Write a method named digit. Sum that accepts an integer as a parameter and returns the sum of the digits of that number. • e. g. digit. Sum(29107) • calculates: 7 + 0 + 1 + 9 + 2 • returns: 19 • If the number is negative, return the negative of the sum digit. Sum( -29107) is -19 Old Method public static int digit. Sum(int n) { int sum = 0; while (n > 0) { // works for both + and - n sum += n % 10; // add last digit to sum n = n / 10; // remove last digit } return sum; } } public class Sum. Digits { public static void main(String[] args) { System. out. println(digit. Sum(29107)); System. out. println(digit. Sum(-29107)); } 19 -19 public static int digit. Sum(int n) { boolean negative = false; if ( n < 0 ){ n = -n; negative = true; } int sum = 0; while (n > 0) { sum += n % 10; // add last digit to sum n = n / 10; // remove last digit } if (negative) sum = -sum; return sum; }} 7

Java modulus, n % m • n is +, n % m is a value between 0 and m-1 • n is negative, n % m is a negative value between 0 and – (m-1) • Examples: 23 % 10 = 3, -23 % 10 = -3 47 % 10 = 7 -47 % 10 = -7 New method that works for Java but may not for other languages. public static int digit. Sum(int n) { int sum = 0; while (n != 0) { // works for both + and - n sum += n % 10; // add last digit to sum n = n / 10; // remove last digit } return sum; } } 8

Returning boolean public static boolean is. Prime(int n) { int factors = 0; for (int i = 1; i <= n; i++) { if (n % i == 0) { factors++; } } } if (factors == 2) { return true; } else { return false; } • Calls to methods returning boolean can be used as tests: if (is. Prime(57)) {. . . } 9

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

Review Logical operators && || ! • Boolean expressions can use logical operators: Operator Description Example Result && (9 != 6) && (2 < 3) true and || (2 == 3) || (-1 < 5) true or not ! !(7 > 0) false • Truth tables of each operator used with boolean values p and q: p true q true false true p && q p || q true false 11 true false p true !p false true

Java Operator Precedence Desciption Operators unary operators ! ++ multiplicative additive + relational equality + * / > >= - % < == -- <= != logical AND && logical OR || assignment = += -= *= %= &&= ||=

Logical Operators Operator Meaning ! NOT && AND Example !minor a < b && b < c (a < b) && (b < c) || OR a < b || a < c (a < b) || (a < c) 13

• The following is illegal: Example if (1 <= x <= 10) { System. out. println("In range"); } • But this is legal: if (1 <= x && x <= 10) { System. out. println("In range"); } Why? Let’s evaluate the first expression 1 <= x <= 10 1 <= x will result in a boolean value true or false. Then we want to apply the <= operator with a boolean on the left and an integer on the right. These are not comparable. For the second, 1 <= x && x <= 10 1 <= x will result in a boolean value true or false. Next the x <= 10 is evaluated to either true or false. Now we have boolean on the left and right of the && and everything works out well. 14

A better but perhaps more complex explanation is the purpose of the two expressions. 1 <= x <= 10 is used in math to show the limits on a variable, x ; x will never be outside those limits. In Java we are testing to see whether or not x is in that range. It is perfectly possible that x is out of the range. 15

if (age > 5 && age < 18) { System. out. println("Why aren't you in school"); } if (hour < 7 || day. equals("Sunday")){ System. out. println("Let me sleep!"); } if (!minor && wallet. Contents > 3) { System. out. println("Here is your beer"); } 16

Boolean logic questions • What is the result of each of the following expressions? int x = 42; int y = 17; int z = 25; • • • 17 true y < x && y <= z x % 2 == y % 2 || x % 2 == z % 2 false x <= y + z && x >= y + z true !(x < y && x < z) true false (x + y) % 2 == 0 || !((z - y) % 2 == 0)

Activity – evaluate these boolean expressions boolean a = true; boolean b = false; boolean c = true; • • a && !b true b && !c false !a || !b true a && b || c true, note: && is higher precedence than || a || b && c true a && b && c false a || b || c true 18

String test methods return boolean Method Description equals(str) whether two strings contain the same characters equals. Ignore. Case(str) whether two strings contain the same characters, ignoring upper vs. lower case starts. With(str) whether one contains other's characters at start ends. With(str) whether one contains other's characters at end contains(str) whether the given string is found within this one if (name. starts. With("Prof")) { System. out. println("When are your office hours? "); if (course. contains(“java")) { System. out. println("Let's talk about objects!"); 19

Boolean question • Use boolean methods to test for rhyming and alliteration. Type two words: Bare blare They rhyme! They alliterate! public class Alliterate. Rhyme { public static void main(String[] args) { Scanner console = new Scanner(System. in); System. out. print("Enter two words: "); String word 1 = console. next(); String word 2 = console. next(); if (rhyme(word 1, word 2)) System. out. println("They rhyme!"); if (alliterate(word 1, word 2)) System. out. println("They alliterate!"); } 20

Boolean answer word 2)) { if (rhyme(word 1, System. out. println("They rhyme!"); } if (alliterate(word 1, word 2)) { System. out. println("They alliterate!"); }. . . alliterate: With this program as written, neither string can be the empty string but one or both could be in the general case. Thus the test for at least one character. // Returns true if s 1 and s 2 end with the same two letters. public static boolean rhyme(String s 1, String s 2) { s 1 = s 1. to. Upper. Case(); s 2 = s 2. to. Upper. Case(); if (s 1. length() >= 2 && s 2. length() >= 2 && s 1. ends. With(s 2. substring(s 2. length() - 2))) return true; else return false; } // Returns true if s 1 and s 2 start with the same letter. public static boolean alliterate(String s 1, String s 2) { s 1 = s 1. to. Upper. Case(); s 2 = s 2. to. Upper. Case(); if (s 1. length() >= 1 && s 2. length() >= 1 && s 1. char. At(0) == s 2. char. At(0)) return true; else return false; return true; } else { return false; }} 21

Getting rid of the s 1 New and s 2 New strings. Do you see why they are not needed here? // Returns true if s 1 and s 2 end with the same two letters. public static boolean rhyme(String s 1, String s 2) { if (s 1. length() >= 2 && s 2. length() >= 2 && s 1. to. Upper. Case(). ends. With(s 1. to. Upper. Case(). substring(s 2 New. length() - 2))) { return true; } else { return false; } } // Returns true if s 1 and s 2 start with the same letter. public static boolean alliterate(String s 1, String s 2) { if (s 1. length() >= 1 && s 2. length() >= 1 && s 1. to. Upper. Case(). char. At(0) == s 2. to. Upper. Case(). char. At(0) ; ) { return true; } else { return false; }} 22

Boolean Zen (cont’d) • Methods that return boolean often have an if/else that returns true or false: public static boolean both. Odd(int n 1, int n 2) { if (n 1 % 2 != 0 && n 2 % 2 != 0) return true; else return false; } – But the code above is unnecessarily verbose. When the test result is true, we return true. When false, return false. // Better public static boolean both. Odd(int n 1, int n 2) { boolean test = (n 1 % 2 != 0 && n 2 % 2 != 0); return test; // Best public static boolean both. Odd(int n 1, int n 2) { return n 1 % 2 != 0 && n 2 % 2 != 0; } 23

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

Improved is. Prime method • The following version utilizes Boolean Zen: public static boolean is. Prime(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 our Rhyme program to use Boolean Zen. 25
![Boolean Zen answer public static void main(String[] args) { Scanner console = new Scanner(System. Boolean Zen answer public static void main(String[] args) { Scanner console = new Scanner(System.](http://slidetodoc.com/presentation_image_h2/664b06287a23179d028c2215a5746afa/image-26.jpg)
Boolean Zen answer public static void main(String[] args) { Scanner console = new Scanner(System. in); System. out. print("Type two words: "); String word 1 = console. next(). to. Lower. Case(); String word 2 = console. next(). to. Lower. Case(); if (rhyme(word 1, word 2)) { System. out. println("They rhyme!"); } if (alliterate(word 1, word 2)) { System. out. println("They alliterate!"); }} // Returns true if s 1 and s 2 end with the same two letters. public static boolean rhyme(String s 1, String s 2) { return s 1. length() >= 2 && s 2. length() >= 2 && s 1. to. Upper. Case(). ends. With(s 2. to. Upper. Case(). substring(s 2. length() - 2)); } } // Returns true if s 1 and s 2 start with the same letter. public static boolean alliterate(String s 1, String s 2) { return s 1. length() >= 1 && s 2. length() >= 1 && s 1. to. Upper. Case(). char. At(0) == s 2. to. Upper. Case(). char. At(0) ; } 26

// Returns true if s 1 and s 2 end with the same two letters. public static boolean rhyme(String s 1, String s 2) { return s 1. length() >= 2 && s 2. length() >= 2 && s 1. to. Upper. Case(). ends. With(s 2. to. Upper. Case(. substring(s 2. length() - 2)); } // Returns true if s 1 and s 2 start with the same letter. public static boolean alliterate(String s 1, String s 2) { return s 1. to. Upper. Case(). starts. With(s 2. to. Upper. Case(). substring(0, 1)); 27

These are probably faster because they work mainly with chars not strings. // Returns true if s 1 and s 2 start with the same letter. public static boolean alliterate(String s 1, String s 2) { return s 1. length() >= 1 && s 2. length() >= 1 && Character. to. Upper. Case(s 1. char. At(0)) == Character. to. Upper. Case(s 2. char. At(0)); } // Returns true if s 1 and s 2 end with the same two letters. public static boolean rhyme(String s 1, String s 2) { return s 1. length() >= 2 && s 2. length() >= 2 && Character. to. Upper. Case(s 1. char. At(s 1. length() - 1)) == Character. to. Upper. Case(s 2. char. At(s 2. length() - 1)) && Character. to. Upper. Case(s 1. char. At(s 1. length() - 2)) == Character. to. Upper. Case(s 2. char. At(s 2. length() - 2)); } 28

Short Circuit Evaluation • When faced with a multiple part logical expression, Java stops evaluating as soon as it has enough information to determine the answer. • if ( (a < b) && (b < c) ) part-1 part-2 If part-1 (a < b ) is false Java does not evaluate part-2. Entire expression is false. if ( (a < b) || (c < b) ). . . If part-1 (a < b ) is true Java does not part-1 part-2 evaluate part-2. Entire expression is true. 29

"Short-circuit" evaluation • Java stops evaluating a test if it knows the answer. – && stops early if any part of the test is false – || stops early if any part of the test is true • The following test will crash if s 2's length is less than 2: // Returns true if s 1 and s 2 end with the same two letters. public static boolean rhyme(String s 1, String s 2) { return s 1. ends. With(s 2. substring(s 2. length() - 2)) && s 1. length() >= 2 && s 2. length() >= 2; } • The following test will not crash; it stops if length < 2: // Returns true if s 1 and s 2 end with the same two letters. public static boolean rhyme(String s 1, String s 2) { return s 1. length() >= 2 && s 2. length() >= 2 && s 1. ends. With(s 2. substring(s 2. length() - 2)); } 30
![public class Short. Circuit { public static void main(String[] args) { System. out. println(rhyme("red, public class Short. Circuit { public static void main(String[] args) { System. out. println(rhyme("red,](http://slidetodoc.com/presentation_image_h2/664b06287a23179d028c2215a5746afa/image-31.jpg)
public class Short. Circuit { public static void main(String[] args) { System. out. println(rhyme("red, red rose", “you lose")); System. out. println(rhyme 2("red, red rose", "e")); System. out. println(rhyme("red, red rose", "e")); } // Returns true if s 1 and s 2 end with the same two letters. public static boolean rhyme(String s 1, String s 2) { return s 1. ends. With(s 2. substring(s 2. length() - 2)) && s 1. length() >= 2 && s 2. length() >= 2; } // Returns true if s 1 and s 2 end with the same two letters. public static boolean rhyme 2(String s 1, String s 2) { return s 1. length() >= 2 && s 2. length() >= 2 && s 1. ends. With(s 2. substring(s 2. length() - 2)); } true false Exception in thread "main" java. lang. String. Index. Out. Of. Bounds. Exception: String index out of rang 1 at java. lang. String. substring(Unknown Source) at Short. Circuit. rhyme(Short. Circuit. java: 15) 31 at Short. Circuit. main(Short. Circuit. java: 9)
![Another example. public static void main(String[] args) { String s = first. Word(" test Another example. public static void main(String[] args) { String s = first. Word(" test](http://slidetodoc.com/presentation_image_h2/664b06287a23179d028c2215a5746afa/image-32.jpg)
Another example. public static void main(String[] args) { String s = first. Word(" test string "); System. out. println(s); } public static String first. Word(String s) { // find start - skip leading spaces int start = 0; while (s. char. At(start) == ' ' && start < s. length()) { start++; } // find end - move past word to next space int end = start; while (s. char. At(end) != ' ' && end < s. length()) { end++; } Works fine for this string. return s. substring(start, end); } start t e s t end s t r i n g 32
![public static void main(String[] args) { String s = first. Word(" testimonial"); System. out. public static void main(String[] args) { String s = first. Word(" testimonial"); System. out.](http://slidetodoc.com/presentation_image_h2/664b06287a23179d028c2215a5746afa/image-33.jpg)
public static void main(String[] args) { String s = first. Word(" testimonial"); System. out. println(s); } public static String first. Word(String s) { // find start - skip leading spaces int start = 0; while (s. char. At(start) == ' ' && start < s. length()) { start++; } // find end - move past word to next space Solution: Reverse these tests. int end = start; while (s. char. At(end) != ' ' && end < s. length()) { end++; end = s. length() if the first } return s. substring(start, end); word’s last letter is in the last place of the string. } start t e s t i m o n i a l end Does not work for this string, array out of bounds error. 33
![public static void main(String[] args) { String s = first. Word(" testimonial"); System. out. public static void main(String[] args) { String s = first. Word(" testimonial"); System. out.](http://slidetodoc.com/presentation_image_h2/664b06287a23179d028c2215a5746afa/image-34.jpg)
public static void main(String[] args) { String s = first. Word(" testimonial"); System. out. println(s); } Solution: Reverse these tests. public static String first. Word(String s) { // find start - skip leading spaces int start = 0; while (s. char. At(start) == ' ' && start < s. length()) { start++; start= s. length() if the string is all } spaces // find end - move past word to next space int end = start; while (s. char. At(end) != ' ' && end < s. length()) { end++; } return s. substring(start, end); } start Does not work for this string, array out of bounds error. 34

public static String first. Word(String s) { // find start - skip leading spaces int start = 0; while (s. char. At(start) == ' ' && start < s. length()) { start++; } // find end - move past word to next space int end = start; while (s. char. At(end) != ' ' && end < s. length()) { end++; } return s. substring(start, end); Now, this works for all cases. } public static void main(String[] args) { String s = first. Word(" testimonial"); System. out. println(s); } start Note: s. substring(0, 0) is “” end start t e s t end t e s t i m o n i a l s t r i n g 35

public static String first. Word(String s) { // find start - skip leading spaces int start = 0; while (start < s. length() && s. char. At(start) == ' ') { start++; } // find end - move past word to next space int end = start; while (end < s. length() && s. char. At(end) != ' ') { end++; } Does this work if s is return s. substring(start, end); the empty string, “”? } public static void main(String[] args) { String s = first. Word(" testimonial"); System. out. println(s); } start t e s t i m o n i a l end 36

The do/while loop (review) • do/while loop: Performs its test at the end of each repetition. – Guarantees that the loop's {} body will run at least once. do { statement(s); } while (test); // Example: prompt until correct password is typed String phrase; do { System. out. print("Type your password: "); phrase = console. next(); } while (!phrase. equals("abracadabra")); 37

De Morgan's Law • De Morgan's Law: Rules used to negate boolean tests. – Useful when you want the opposite of an existing test, as is often the case when using a do … while. Original Expression a && b a || b Negated Expression !a || !b !a && !b Alternative !(a && b) !(a || b) This is obviously the easiest form. Example: Get out of the loop when the random number generated is odd and has more than 5 factors. Thus we want to get out of the loop when x%2 = =1 && num. Factors (x) > 5. So we want to continue the loop when that is not true, !(x%2 ==1 && count. Factors (x) > 5. (This is silly but illustrates the point. ) do { x = rand. next. Int(); } while (!(x%2 == 1 && num. Factors (x) > 5) ); System. out. printf("Your odd number is %d", x); Your odd number is 1565707745 38

Activity Write a method to play the guess the secret number game Try to guess my number 1 -100. Guess? 50 too low Guess? 75 too low Guess? 85 You got it! Here is the start of the method. Use a do / while loop. public static void guess(Scanner console, int secret. Num) { System. out. println("Try to guess my number 1 -100. "); int guess; . . . Use a do. . while because you know you will make at least one guess. 39
![import java. util. *; public class Guess. Game { public static void main(String[] args) import java. util. *; public class Guess. Game { public static void main(String[] args)](http://slidetodoc.com/presentation_image_h2/664b06287a23179d028c2215a5746afa/image-40.jpg)
import java. util. *; public class Guess. Game { public static void main(String[] args) { Random rand = new Random(); Scanner console = new Scanner(System. in); guess(console, rand. next. Int(100)+ 1); } public static void guess(Scanner console, int secret. Num) { System. out. println("Try to guess my number, 1 -100: "); int guess; Try to guess my number, 1 do { 100: System. out. print("Guess: "); Guess: 50 guess = console. next. Int(); too high if ( guess < secret. Num ) Guess: 25 System. out. println("too low"); too high Guess: 13 else if ( guess > secret. Num ) System. out. println("too high"); too low Guess: 19 } while (!(guess == secret. Num)); too high System. out. println("You got it!"); } } Guess: 16 You got it! 40

More general material about boolean variables and while loops. 41

Java has a class Character that has useful static methods for operating on characters. Character. is. Digit(ch) Character. is. Letter(ch) Character. is. Lower. Case(ch) Character. is. Upper. Case(ch) Character. to. Lower. Case(ch) Character. to. Upper. Case(ch) Character. get. Numeric. Value(ch) example: char ch = '? '; if (Character. is. Letter(ch)) { System. out. println(ch + " is a letter"); else System. out. println(ch + " is not a letter"); } Output: ? is not a letter

Boolean practice questions • Write a method named is. Vowel that returns whether a char is a vowel (a, e, i, o, or u), caseinsensitively. – is. Vowel('q') returns false – is. Vowel('A') returns true – is. Vowel('e') returns true • Change the above method into an is. Non. Vowel that returns whether a String is any character except a vowel. – is. Consonant('q') returns true – is. Consonant('A') returns false – is. Consonant('e') returns false 43
![public class Vowels. And. Consonants. Char { public static void main(String[] args) { String public class Vowels. And. Consonants. Char { public static void main(String[] args) { String](http://slidetodoc.com/presentation_image_h2/664b06287a23179d028c2215a5746afa/image-44.jpg)
public class Vowels. And. Consonants. Char { public static void main(String[] args) { String stuff = "This is, a string of Stuff"; for ( int i = 0; i < stuff. length(); i++ ){ if (is. Vowel(stuff. char. At(i))) System. out. println(stuff. char. At(i) + " is a vowel. "); else if (is. Consonant(stuff. char. At(i))) System. out. println(stuff. char. At(i) + " is a consonant. "); else System. out. println(stuff. char. At(i) + " is not a letter. "); } } // Enlightened version of is. Vowel. public static boolean is. Vowel(char s) { return Character. to. Lower. Case(s) == 'a' || Character. to. Lower. Case(s) == 'e' || Character. to. Lower. Case(s) == 'i' || Character. to. Lower. Case(s) == 'o' || Character. to. Lower. Case(s) == 'u'; } // Enlightened "Boolean Zen" version of is. Consonant. public static boolean is. Consonant(char s) { return Character. is. Letter(s) && !is. Vowel(s); }} 44

T is a consonant. h is a consonant. i is a vowel. s is a consonant. is not a letter. i is a vowel. s is a consonant. , is not a letter. a is a vowel. is not a letter. s is a consonant. t is a consonant. r is a consonant. i is a vowel. n is a consonant. g is a consonant. is not a letter. o is a vowel. f is a consonant. is not a letter. S is a consonant. t is a consonant. u is a vowel. f is a consonant. public class Vowels. And. Consonants. Char { public static void main(String[] args) { String stuff = "This is, a string of Stuff"; for ( int i = 0; i < stuff. length(); i++ ){ if (is. Vowel(stuff. char. At(i))) System. out. println(stuff. char. At(i) + " is a vowel. "); else if (is. Consonant(stuff. char. At(i))) System. out. println(stuff. char. At(i) + " is a consonant. "); else System. out. println(stuff. char. At(i) + " is not a letter. "); } } 45

Print the prime factors of a number separated by commas (fence post problem). import java. util. *; The boolean variable is public class Prime. Factors { there to record if a value public static void main(String[] args) { Scanner console = new Scanner(System. in); has yet been printed. When the first value is System. out. print("Enter a positive integer: "); printed, it is not followed int val = console. next. Int(); by a comma. From then System. out. print("The prime factors are "); on the values are printed boolean print. Yet = false; // fence post as a comma followed by int count = 0; the value. for ( int i = 2; i <= val; i++ ) if (count. Factors(i) == 2 ) Enter a positive integer: 50 if (val % i == 0) The prime factors are 2, 5 { 2 total prime factors if ( !print. Yet ) { print. Yet = true; Enter a positive integer: 49 System. out. print(i); The prime factors are 7 } 1 total prime factors else Enter a positive integer: 30 System. out. print(", " + i ); The prime factors are 2, 3, 5 count++; 3 total prime factors } System. out. println("n" + count + " total prime factors "); 46 }

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) 47

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. next. Int(30) + 1; System. out. print(num + " "); } } if (num == 7) { return true; } return false; // found lucky 7; can exit now // if we get here, there was no 7 – Returns true immediately after 7 is found. – If 7 isn't found, the loop continues drawing lotto numbers. – If none of the ten are, the loop ends and we return false. 48

Boolean return questions • has. An. Odd. Digit : returns true if any digit of an integer is odd. – has. An. Odd. Digit(4822116) returns true – has. An. Odd. Digit(2448) returns false • all. Digits. Odd : returns true if every digit of an integer is odd. – all. Digits. Odd(135319) returns true – all. Digits. Odd(9174529) returns false • is. All. Vowels : returns true if every char in a String is a vowel. – is. All. Vowels("e. Io") returns true – is. All. Vowels("oink") returns false 49

Boolean return answers public static boolean has. An. Odd. Digit(int n) { while (n != 0) { if (n % 2 == 1) { // check whether last digit is odd return true; } n = n / 10; } return false; } public static boolean all. Digits. Odd(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 is. All. Vowels(String s) { for (int i = 0; i < s. length(); i++) { String letter = s. substring(i, i + 1); if (!is. Vowel(letter)) { return false; } } return true; 50
![public class First. Word. Good { public static void main(String[] args) { String s public class First. Word. Good { public static void main(String[] args) { String s](http://slidetodoc.com/presentation_image_h2/664b06287a23179d028c2215a5746afa/image-51.jpg)
public class First. Word. Good { public static void main(String[] args) { String s = first. Word(" hello there " ); System. out. println(s + " " + s. length()); } public static String first. Word(String s) { // find start - skip leading spaces int start = 0; while (start < s. length() && s. char. At(start) == ' ' ) start++; // find end - move past word to next space int end = start; while (end < s. length() && s. char. At(end) != ' ') end++; return substring(s, start, end); } public static String substring(String s, int start, int end){ if ( start == end) return ""; String ret. String = ""; for ( int i = start; i < end; i++) ret. String += s. char. At(i); return ret. String; } } 51

Boolean practice questions • Write a method named is. Vowel that returns whether a String is a vowel (a, e, i, o, or u), caseinsensitively. – is. Vowel("q") returns false – is. Vowel("A") returns true – is. Vowel("e") returns true • Change the above method into an is. Non. Vowel that returns whether a String is any character except a vowel. – is. Non. Vowel("q") returns true – is. Non. Vowel("A") returns false – is. Non. Vowel("e") returns false 52

public static boolean is. Vowel(String s) { Hint: Just check for each of the 5 vowels public static boolean is. Non. Vowel(String s) { Hint: Use is. Vowel. 53

Boolean practice answers // Enlightened version of is. Vowel. public static boolean is. Vowel(String s) { return s. equals. Ignore. Case("a") || s. equals. Ignore. Case("e") || s. equals. Ignore. Case("i") || s. equals. Ignore. Case("o") || s. equals. Ignore. Case("u"); } // Enlightened "Boolean Zen" version of is. Non. Vowel. public static boolean is. Non. Vowel(String s) { return !(s. equals. Ignore. Case("a") || s. equals. Ignore. Case("e") || s. equals. Ignore. Case("i") || s. equals. Ignore. Case("o") || s. equals. Ignore. Case("u")); } // or, return !is. Vowel(s); 54
- Slides: 54