Control Structures: As a build up from the previous question, consider 3 possible scenario of input : A character, number or word. You program should the 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 and finally if a word is entered the system should check if it’s a palindrome or not. Sample Run1 Sample Run3 Enter a character, number or word: c Enter a character, number or word: 7 Output1: C is not a vowel Output3: 7 is a prime number Sample Run2 Enter a character, number or word: programming Output2: Programming is not a palindrome
import java.util.Scanner;
import java.math.*;
import java.io.*;
import java.util.*;
import java.lang.StringBuilder;
public class Sample{
public static void main(String args[]) {
// read keyboard input
Scanner in = new Scanner(System.in);
String input = in.nextLine();
// check for vowels
if(input.matches("[aeiouy]")){
System.out.println("it’s a vowel");
// check for number
}else if(input.matches("\\d+")){
int number = Integer.parseInt(input);
BigInteger bigInteger = BigInteger.valueOf(number);
// check for prime number
boolean probablePrime = bigInteger.isProbablePrime((int) Math.log(number));
if(probablePrime){
System.out.println("it’s a prime");
}else{
System.out.println("it’s not a prime");
}
// check for word
}else if(input.length() > 1){
// reverse word then compare without upper case
int boolPalindrome = input.compareToIgnoreCase(new StringBuilder(input).reverse().toString());
// check for palindrome from result
if(boolPalindrome == 0){
System.out.println("It's a palindrome");
}else{
System.out.println("It's not a palindrome");
}
}else{
System.out.println("it’s not a vowel");
}
}
}
Comments
Leave a comment