Question:
Write a Java Program to read a string from the user and fetch the middle characters that feature in the center of the string from the input string and return it as string output.
- 1. The Minimum string size should be of 3 characters. If not, print “The string <string> is too short”.
- 2. String should have only Alphabets. If not, print “The string should not have <special character/ numbers>”.
Assumption:
The Input string should be without space.
Sample Input 1:
Enter the String:
This
Sample Output 1:
Middle characters:
hi
Sample Input 2:
Enter the String:
Paragraph
Sample Output 2:
Middle characters:
g
Sample Input 3:
Enter the String:
am
Sample Output 3:
The string am is to short
Sample Input 1:
Enter the String:
a??@e
Sample Output 1:
Middle characters:
Code:
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println(“Enter the sting:”);
String str = sc.nextLine();
char ch[] = str.toLowerCase().toCharArray();
int c=0;
int v=0;
String sp=””;
if(str.length()<3){
System.out.println(“The string should not have “+str+” is too short”);
}
else{
for (int i=0;i<ch.length;i++) {
if (ch[i] >= ‘a’ && ch[i] <= ‘z’) {
c++;
} else {
sp += ch[i];
v++;
}
}
if(ch.length!=c){
System.out.println(“This string should not have “);
System.out.println(sp);
}
else if(ch.length==c){
System.out.println(“Middle Characters:”);
if(ch.length%2==0){
String out = “”+ch[(ch.length/2)-1]+ch[(ch.length/2)];
System.out.println(out);
}
else{
String out = “”+ch[ch.length/2];
System.out.println(out);
}
}
}
}
}