ABOUT THIS PROGRAM
This program takes a string from the user and counts the total number of words in it. No matter how many white spaces are there in the string, it will only count the number of words.
(i) Hi this is Rupam.
(ii) Hi this is Rupam.
Here to find the total number of words in a string, we have to count the number of spaces. Because every word in a sentence is separated by a whitespace, right? The total number of spaces + 1 will be the total number of words. So if we count the number of spaces in a sentence, we will get the total number of words easily.
Ex: This program will count the number of words.
Here total number of spaces= 7
So total number of words= 7+1= 8
Now there is a problem in this logic. This logic will only work if there is only one space between every word. What if there are more than one white spaces between the words? The result will be wrong.
So we have to apply another condition along with the above condition. Count the space only if it is not preceded by any other white space.
This program will count the number of words.
(i) Here we are taking a string from the user and assigning it to a variable.
(ii) Return the length of the string using length() method.
(iii) Using For loop we are checking each character (charAt method) in the string given by user.
Inside the for loop we are using If..else statement to check if the character is a whitespace or not. We are also checking if it is preceded by any other white space or not.
The condition will satisfy only if both the above two conditions are true.
(iv) If it satisfies, increment the word count by one.
public class WalkyTechy
public static void main(String args)
Scanner s = new Scanner(System.in);
System.out.println("Enter a string: ");
if(str.charAt(i)==' ' && str.charAt(i-1)!=' ')
System.out.println("Total Number of words= "+word);
Enter a string:
This program counts the number of words.
Total Number of words= 7