Answer to Question #308720 in Java | JSP | JSF for denard

Question #308720

Control Structures: 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:

  • In case the input is a character it should indicate if it’s a vowel or not
  • when a number is entered then it’s should check if it’s a prime
  • Finally, if a word is entered the system should check if it’s a palindrome or not.

     Sample Run 1                               Sample Run 3

             Enter a character, number or word : c                  Enter a character, number or word : 

             Output 1 : C is not a vowel                                     Output 3 : 7 is a prime number  

Sample Run 2

              Enter a character, number or word: programming

Output 2: Programming is not a palindrome

 


1
Expert's answer
2022-03-10T10:19:04-0500


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();
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS