Random Java Programs: Count the number of words in a paragraph.

 A paragraph is a collection of words in a format and has a meaning. To count the number of words in a paragraph, let us follow the steps. let us implement it.

Logic behind the program:

  • First, read the input paragraph from the command line.
  • Check for emptiness, use isEmpty() function.
  • If the value is true, then print “The paragraph does not have any words”.
  • Otherwise, start the process.
  • Let us split the words by space and add the count value.
  • Finally, print the count value.

Program implementation:

//Built in header file inclusion

import java.util.Scanner;

// create a public class with main function

public class countIt {

    public static void main(String[] args) {

        // let us create the scanner object

        Scanner scanner1 = new Scanner(System.in);

       // ask the user to enter the Paragraph

        System.out.println("Enter a Paragraph:");

        String ipara = scanner1.nextLine();

      // let us check whether paragraph is empty or not

        if (ipara.trim().isEmpty()) {

            System.out.println("The paragraph does not have any words");

        } else {

            // Split the paragraph into words using spaces

            String[] iWords = ipara.trim().split("\\s+");

            int wc = iWords.length;

         // print the count value

            System.out.println("The number of words in the Paragraph: " + wc);

        }

        scanner1.close();

    }

}

Output:

Just compile and run the program to get the output.

C:\raji\blog>javac countIt.java

C:\raji\blog>java countIt

Enter a Paragraph:

once there lived a man whose name is David. He is tall and plays music well. He wants to become a music director.But he does not have any degree in music.He worked hard and learnt all types of music.Finally, he became a music director.

The number of words in the Paragraph: 44

This is one of the random java programs to count the number of words in a paragraph given by the user. Hope this program is helpful to you. Keep coding!!!!

No comments:

Post a Comment