5-8 Word

Post date: Apr 6, 2014 4:39:35 PM

/*

Write a program WordCounter that calls a function that accepts a string (from main) and

returns the number of words contained in the string. For instance, if the string argument is “I love

java Programming” the function should return the number 4.

*/

package word;

import java.util.Scanner;

public class Word

{

public static void main(String[] args)

{

Scanner scan=new Scanner(System.in);

System.out.print("Enter your string : ");

System.out.println("Number of words contained in the string : "+WordCounter(scan.nextLine()));

}

public static int WordCounter(String s)

{

Scanner input=new Scanner(s);

int count=0;

while(input.hasNext())

{

count++;

input.next();

}

return count;

}

}

.............................................................................................

run:

Enter your string : i love java programming

Number of words contained in the string : 4

BUILD SUCCESSFUL (total time: 11 seconds)