Latest :

Simple Java Program To Count Syllables | Java Programs

Count syllables in large string in Java –  This specific article will be dealing with the Java program to count syllables. Suitable examples, as well as sample output, will be provided.

This code is for counting the number of words in a user input string using Java language.

  • The problem here is to count the number of words in a string that is defined by user input.
  • Our constraint here is the inability to get the correct word count in the event of the user input string containing a hyphen at the beginning of the string.
  • The input here is a sentence containing hyphens in place of white spaces in the form of a string input by the user.
  • The output here is the count of the number of words present in the user-defined input string.
 

Output – 1:

  • Solution:
  1. The first line in the main method declares int i and int count and initializes the value of count to 1.
  2. Then, a new Scanner class object is initialized and a reference variable sc is set to represent the object. This class is used to take user input in Java. Scanner class is part of the java.util package and hence the import statement, in the beginning, is stated to import the functionality of the specified class.
  3. The next line prints a statement to the console instructing the user to enter a string.
  4. The .nextLine() method is called by the Scanner object sc. This method reads a line of user input of a string value and stores it to the string variable name.
  1. This loop iterates over all the characters (including the hyphens and other special characters which are also considered as characters in Java) in the user-defined string.
  2. For each iteration, a conditional statement checks whether the character in consideration is a hyphen and the next character is not a hyphen. It is essentially checking if the given character is a hyphen between two words.
  3. The count is incremented by 1 if this condition is satisfied. Keep in mind that the first word is not counted using this technique and hence the value of count is initialized to 1 and not 0.
  4. The print statement at the end of the main method prints out the input and the counted number of words in the input as the output for the Java program to count syllables.

x

Check Also

Java Program To Display Transpose Matrix | 3 Ways

Java Program to display/print the transpose of a given matrix.  The following program to print ...