Answer to Question #304433 in Java | JSP | JSF for Nguu

Question #304433

 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.
1
Expert's answer
2022-03-02T01:17:25-0500
import java.util.Scanner;

public class Main {

    public static boolean isPrime(int number) {
        boolean[] primes = new boolean[number + 1];
        for (int i = 2; i < primes.length; i++) {
            for (int j = i * i; j < primes.length; j += i) {
                primes[j] = true;
            }
        }
        return !primes[number];
    }

    public static boolean isPalindrome(String line) {
        for (int i = 0; i < line.length() / 2; i++) {
            if (line.charAt(i) != line.charAt(line.length() - 1 - i)) {
                return false;
            }
        }
        return true;
    }

    public static boolean isVowel(String line) {
        line = line.toLowerCase();
        String[] vowels = {"a", "e", "i", "o", "u"};
        for (String vowel : vowels) {
            if (line.charAt(0) == vowel.charAt(0)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String line = in.nextLine();
        try {
            int number = Integer.parseInt(line);
            System.out.println("Prime: " + isPrime(number));
        } catch (NumberFormatException e) {
            if (line.length() == 1) {
                System.out.println("Vowel: " + isVowel(line));
            } else {
                System.out.println("Palindrome: " + isPalindrome(line));
            }
        }
    }
}

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