Question #124059

Write Java Code to input a complete paragraph, as an input. Further, read a single character/letter. Finally, you are required to [Marks = 02]

(a) - Count the number of Words in the paragraph starts with the letter taken as input from the user.

(b)- Display the total number of words in the paragraph

Implement all this scenario using OOP Concepts of Java. Your code should also take care of the exceptions that can occur while dealing with Strings.

Expert's answer

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please input paragraph: ");
      String res = "";
      String current = sc.nextLine();
      while(!current.equals("")){
          res += current + " ";
          current = sc.nextLine();
      }
      String [] resArr = res.split(" ");
      System.out.println("Please input prefix: ");
      String prefix = sc.nextLine();
      ArrayList<String> resList = new ArrayList<>();
      for(String str: resArr)
      {
          if(str.startsWith(prefix)){
              resList.add(str);
          }
      }
        System.out.println("Result: ");
      for(String str: resList){
          System.out.println(str);
      }
        System.out.println("Total number of words: "+resArr.length);
        System.out.println("Total number of words that starts with prefix: "+resList.size());
    }
}
LATEST TUTORIALS
APPROVED BY CLIENTS