// Zorah Fung, CSE 142 // Examples of methods that return booleans import java.util.*; public class BooleanMethods { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.print("What is your age? "); int age = console.nextInt(); if (isPrime(age)) { System.out.println("Welcome to the prime party!"); } System.out.println(bothOdd(5, 7)); // true System.out.println(bothOdd(6, 4)); // false System.out.println(bothOdd(5, 4)); // false System.out.println(bothOdd(0, 7)); // false System.out.println(bothOdd(1, 5)); // true System.out.println(bothOdd(-5, -7)); // true System.out.println("banana: " + hasVowel("banana")); System.out.println("crwth: " + hasVowel("crwth")); // valid word. great for scrabble } // returns whether a value is a prime or not public static boolean isPrime(int value) { return factors(value) == 2; // Bad boolean zen! // int factors = factors(value); // if (factors == 2) { // return true; // } else { // return false; // } } // 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 num1, int num2) { boolean num1Odd = num1 % 2 != 0; boolean num2Odd = num2 % 2 != 0; return num1Odd && num2Odd; } // Returns true if the given word contains a vowel, false otherwise public static boolean hasVowel(String word) { word = word.toLowerCase(); for (int i = 0; i < word.length(); i++) { char c = word.charAt(i); if (isVowel(c)) { return true; } } return false; // must look at all letters before returning false } // Returns true if the given lowercase letter is a vowel, false otherwise // Note: the slides have a different version of isVowel that takes a String // as a parameter, which requires the use of the .equals string method public static boolean isVowel(char c) { boolean vowel = c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'; return vowel; } // Returns true if the given lowercase letter is not a vowel (consonant), false otherwise public static boolean isNonVowel(char c) { // Equivalent to !isVowel(c) // In order to negate the expression from isVowel, we both negate the tests // in each expression, as well as flip the logical operator from || to && using // DeMorgan's Law return c != 'a' && c != 'e' && c != 'i' && c != 'o' && c != 'u'; } }