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 MyTask{
public static void main(String args[]) {
// read keyboard input
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
// check for vowels
if(s.matches("[aeiouy]")){
System.out.println("it’s a vowel");
// check for number
}else if(s.matches("\\d+")){
int number = Integer.parseInt(s);
BigInteger primeNumber = BigInteger.valueOf(number);
// check for prime number
boolean boolPrimeNumber = primeNumber.isProbablePrime((int) Math.log(number));
if(boolPrimeNumber){
System.out.println("it’s a prime");
}else{
System.out.println("it’s not a prime");
}
// check for word
}else if(s.length() > 1){
// reverse word then compare without upper case
int palindromNumber = s.compareToIgnoreCase(new StringBuilder(s).reverse().toString());
// check for palindrome from result
if(palindromNumber == 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