Wednesday, 11 June 2025

Word Counter Java Program

Write a method that accepts a string object as an argument and returns the number of words it contains. For instance, if the argument is "Four score and seven years ago" the method should return the number 6. Demonstrate the method in a program that asks the user to input a string and then passes it to the method. The number of words in the string should be displayed on the screen. 


Code:

package programmingChallenges;
import java.util.*;
public class WordCounter {
public static void main(String[]args)
{
Scanner sc = new Scanner(System.in);
String str,str2;
int a=1,b,c=0,num;

System.out.print("Enter String: ");
str = sc.nextLine();
b = str.indexOf(' ');
while(b!=-1)
{
a++;
b= str.indexOf(' ',b+1);
}
while(str.charAt(c)==' ')
{
a=a-1;
c++;
}
System.out.println("There are "+a+" words in the string.");

System.exit(0);
}
}



No comments:

Post a Comment