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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
import java.util.Scanner; class CountSyllables { public static void main(String arg[]) { int i,count=1; Scanner sc=new Scanner(System.in); System.out.println("Enter the string"); String name = sc.nextLine(); for(i=0;i<name.length();i++) { if(name.charAt(i)=='-'&&name.charAt(i+1)!='-') { count++; } } System.out.print("NumberSyllables("+name+")---------->"+count); } } |
Output – 1:
- Solution:
- The first line in the main method declares int i and int count and initializes the value of count to 1.
- 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.
- The next line prints a statement to the console instructing the user to enter a string.
- 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 2 3 4 5 |
for(i=0;i<name.length();i++) { if(name.charAt(i)=='-'&&name.charAt(i+1)!='-') { count++; } } |
- 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.
- 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.
- 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.
- 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.
1 2 3 |
Enter the string welcome-to-java-tutoring-com NumberSyllables(welcome-to-java-tutoring-com)---------->5 |