// Helene Martin, CSE 142 // Several methods that return booleans // goal: demonstrate that boolean is a type like any other // show examples of 1-line boolean methods that increase readability // show "boolean zen" import java.util.*; public class BooleanDemo { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("What's your age? "); int age = console.nextInt(); boolean canVote = age >= 18; System.out.println(canVote); boolean isSunny = true; if (canVote && isSunny) { System.out.println("To the polls!"); } System.out.println(isPrime(age)); // full coverage tests for bothOdd System.out.println(); System.out.println("testing bothOdd"); System.out.println(bothOdd(12, 14)); System.out.println(bothOdd(13, 14)); System.out.println(bothOdd(12, 13)); System.out.println(bothOdd(13, 15)); // should also test isVowel and isNonVowel } // isPrime returns true if parameter is prime, false otherwise public static boolean isPrime(int value) { return factors(value) == 2; // very zen // bad boolean zen: /*if (prime) { // prime == true return true; } else { // prime == false return false; }*/ /*boolean prime = factors == 2; return prime;*/ } // counts and returns the factors of a given number public static int factors(int value) { int factors = 0; for (int i = 1; i <= value; i++) { if (value % i == 0) { factors++; } } return factors; } // bothOdd returns true if both parameters are odd, false otherwise public static boolean bothOdd(int val1, int val2) { // boolean firstOdd = val1 % 2 != 0; // boolean secondOdd = val2 % 2 != 0; // return firstOdd && secondOdd; return val1 % 2 != 0 && val2 % 2 != 0; } // isVowel returns whether a String is a vowel (a, e, i, o, or u), // case-insensitively. public static boolean isVowel(String s) { s = s.toLowerCase(); // or use equalsIgnoreCase return s.equals("a") || s.equals("e") || s.equals("i") || s.equals("o") || s.equals("u"); } // isNonVowel returns whether a String is any character except a vowel. public static boolean isNonVowel(String s) { //s = s.toLowerCase(); //return !s.equals("a") && !s.equals("e" ... De Morgan's law return !isVowel(s); } }