As a build-up from the previous question, consider 3 possible scenarios of input: A character, number, or word. Your program should then do the following:
Sample Run 1 Sample Run 3
Enter a character, number or word : c Enter a character, number or word : 7
Output 1 : C is not a vowel Output 3 : 7 is a prime number
Enter a character, number or word: programming
Output 2: Programming is not a palindrome
import java.util.*;
class App {
static boolean isPrime(int number) {
int i;
if (number < 2) {
return false;
}
if (number == 2 || number == 3) {
return true;
}
for (i = 2; i <= Math.sqrt(number * 1.0); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
static boolean isVowel(String word) {
if (word.toLowerCase().charAt(0) == 'a' || word.toLowerCase().charAt(0) == 'e'
|| word.toLowerCase().charAt(0) == 'i' || word.toLowerCase().charAt(0) == 'o'
|| word.toLowerCase().charAt(0) == 'u') {
return true;
}
return false;
}
static boolean isPalindrome(String word) {
int index = 0;
int length = word.length() - 1;
while (length > index) {
if (word.charAt(index) != word.charAt(length)) {
return false;
}
index++;
length--;
}
return true;
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a character, number or word: ");
String input = keyboard.next();
try {
int inputInt = Integer.valueOf(input);
if (isPrime(inputInt)) {
System.out.println(input + " is a prime number");
} else {
System.out.println(input + " is not a prime number");
}
} catch (NumberFormatException e) {
if (input.length() == 1) {
if (isVowel(input)) {
System.out.println(input + " is a vowel");
} else {
System.out.println(input + " is not a vowel");
}
} else {
if (isPalindrome(input)) {
System.out.println(input + " is a palindrome");
} else {
System.out.println(input + " is not a palindrome");
}
}
}
keyboard.close();
}
}
Comments
Leave a comment