// Marty Stepp, CSE 142, Autumn 2008 // This file contains several logical methods we wrote in class to practice // for the midterm. You can test the output of methods like these on our // Practice-It system on the course web site. import java.util.*; // for Scanner, Random public class LogicMethods { public static void main(String[] args) { System.out.println("digit sum of 29107: " + digitSum(29107)); System.out.println(); System.out.println("is vowel Q: " + isVowel("Q")); System.out.println("is vowel a: " + isVowel("a")); System.out.println("is vowel E: " + isVowel("E")); System.out.println("is vowel x: " + isVowel("x")); System.out.println("is vowel McCain: " + isVowel("McCain")); System.out.println(); System.out.println("is all vowels eIEiO: " + isAllVowels("eIEiO")); System.out.println("is all vowels oink: " + isAllVowels("oink")); System.out.println("is all vowels Obama: " + isAllVowels("Obama")); System.out.println("is all vowels AOi: " + isAllVowels("AOi")); } // Returns the sum of the digits of the given integer. // For example, digitSum(29107) returns 2+9+1+0+7 or 19. public static int digitSum(int n) { n = Math.abs(n); // for negative numbers // compute cumulative sum of digits int sum = 0; while (n != 0) { int digit = n % 10; // 7 n = n / 10; // 2910 sum = sum + digit; } return sum; } // Returns true if every character of the given String is a vowel (aeiou). // Returns false if any character is a non-vowel. public static boolean isAllVowels(String s) { for (int i = 0; i < s.length(); i++) { // charAt String letter = s.substring(i, i+1); if (!isVowel(letter)) { return false; } } return true; } // Returns true if the given String is a vowel (aeiou, case-insensitive). // Returns false for all other Strings. public static boolean isVowel(String s) { s = s.toLowerCase(); // "Boolean Zen" - we can directly return the result of a logical test return (s.equals("a") || s.equals("e") || s.equals("i") || s.equals("o") || s.equals("u")); /* // longer version - also works but not as zen-like if (s.equals("a") || s.equals("e") || s.equals("i") || s.equals("o") || s.equals("u")) { return true; } else { return false; } */ } }