Let's write a program to let user write a sentence and count the words in the entered sentence -
I have already explained in my earlier post - How to get input characters and strings from console, how to let the user enter the characters using the keyboard through Scanner class and nextLine() method. We know String is a class and it has methods to manipulate the strings and characters, we will see new method split(). You can get all the information about String class through API documentation.
Create a logic
- We need to prompt the user to enter the sentence. The program reads the sentence using method nextLine() of Scanner class. I have already explained how to get any type of text from the user using the class Scanner in post Get input from console. As soon as the user presses the enter button, the nextLine() reads the whole text entered by the user and returns the String object.
- Now, the program needs to separate words. A sentence has words separated by space " ". String class has a method split(), which creates an array of strings by separating text with given separator passed as a parameter to the method.
- By using space " " as a separator, the split() method returns array of all the words entered by the user. We have discussed arrays already in the post Arrays. The length of an array will tell us how many words user has entered.
Program to find the count of words in a sentence entered by user
import java.io.IOException;
import java.util.Scanner;
public class Sentence {
public static void main(String args[]) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the sentence:");
String str = sc.nextLine();
String words[] = str.split(" ");
int wordCount = words.length;
System.out.println("Word Count is " + wordCount);
}
}
Let's analyze above program using the logic steps above -
String str = sc.nextLine();
The program reads the sentence entered by the user using method nextLine() and the returned string is assigned to the String variable str.
String words[] = str.split(" ");
String str is converted to a String array words[] using the split method and separator as space " ".
int wordCount = words.length;
Each array has a property length which returns the number of elements in the array. In this case, words.length; returns the number of words in the sentence.
if(prime) System.out.print(i + " ");
Output will be like -
Enter the sentence:
Do more of what makes you Happy!!
Word Count is 7
Note: Here in the above program, we used Scanner class and String class methods. These two classes are important classes and will be used more later. You can find all the detailed documentation regarding Scanner class, String class and Array in the links.
No comments:
Post a Comment