Tuesday, October 23, 2012

Word Counting BlueJ Program Using Different Techniques


This is a very common program for ICSE students – take a string and count the number of words in it. In this post I have shown you different techniques to do the program.

In the first program I have used ‘indexOf ()’ and ‘substring ()’ functions of String class to perform the program.

import java.io.*;

class A

{

 String name;

 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

 int i,j;

 void take () throws Exception

 {

  System.out.println("Enter name with surname and middle name (if any):");

  name=br.readLine();

  }

   void show()

   {

    i=1;

    while(true)

    {

    j=name.indexOf(' ');

    if(j< 0)<0 o:p="o:p">

    break;

    i++;

    name=name.substring(j+1);

    }

    System.out.println("Number of words in the name="+i);

    }

    public static void main(String args[])throws Exception

    {

     A ob=new A();

     ob.take();

     ob.show();

     }

     }

 In the second program, simply length of the string is used and each and every character of the string are checked for space.

import java.io.*;

class A

{

 String name;

 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

 int i,j;

 void take () throws Exception

 {

  System.out.println("Enter name with surname and middle name (if any):");

  name=br.readLine();

  }

   void show()

   {

   int len;

    i=1;

    len=name.length();

    for(j=0;j< len;j++)

    {

    if(name.charAt(j)==' ')

    i++;

    }

    System.out.println("Number of words in the name="+i);

    }

    public static void main(String args[])throws Exception

    {

     A ob=new A();

     ob.take();

     ob.show();

     }

     }


No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner