wap in Java to input a string and check if it's a three-word sentence, outputs the middle word. otherwise, outputs a suitable error message
Answers
Answered by
2
Required Answer:-
Question:
- Write a Java program to input a string and if it is a three-word sentence, display the middle word or else, display a suitable error message.
Solution:
Here is the program.
import java.util.*;
public class StringOp {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.print("Enter a string: ");
String s=sc.nextLine();
String a[]=s.split(" ");
if(a.length==3) {
System.out.println("String has three words.");
System.out.println("Middle Word is: "+a[1]);
}
else
System.out.println("Error.");
sc.close();
}
}
Explanation:
- We will ask the user to enter the sentence. Now, we will split the sentences into words and store them in array. If the array length is three, then there must be three words present in it. Middle word is placed at index 1 (since first index is 0 and second index is 1, second index contains the middle word). Now, we will display the middle word.
- If there is more then 3 words or less than 3 words, then an error message is displayed.
Output is attached.
Attachments:
Similar questions
Physics,
1 month ago
Computer Science,
3 months ago
Math,
3 months ago
Chemistry,
9 months ago
Science,
9 months ago