Thursday, April 7, 2011

BlueJ Program On Displaying Word From A Sentence With Maximum Length

In this program we will retrieve the words from a sentence and the word with maximum length will be displayed.

How to proceed on this program

.

In the first program, I have used StringTokenizer class of java.util package to break the entered sentence into words. StringTokenizer class has several overloaded version of constructors and one of them is ‘StringTokenizer(String s)’. This constructor breaks the string into tokens, means words with blank space as the delimitor. The function ‘nextToken()’ of StringTokenizer class is used here to access the tokens, here the words and length of each word is checked with the previous maximum length to find out the word with maximum length. The function ‘hasMoreTokens()’ of StringTokenizer class is a boolean return type function which determines whether there is any token in the StringTokenizer object or not.

Codes of the program



import java.io.*;
import java.util.*;
class Word
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str1,s,maxs;
StringTokenizer stk;
int len=0;
public void take() throws Exception
{
System.out.println("Enter the sentence:");
str1=br.readLine();
stk=new StringTokenizer(str1);

while(stk.hasMoreTokens())
{
s=stk.nextToken();
if(s.length()>len)
{
len=s.length();
maxs=s;
}
}
System.out.println("Word with maximum length="+maxs);
System.out.println("And it's length="+len);
}
public static void main(String args[]) throws Exception
{
Word ob=new Word();
ob.take();
}
}

The same program is done here without StringTokenizer class. Here in this program we have used ‘indexOf()’ function of String class to break the sentence into words and the same process is adapted as the above program to find the word with maximum length.

import java.io.*;
class Word
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str,s,maxs;
int i,len=0;
public void take() throws Exception
{
System.out.println("Enter the sentence:");
str=br.readLine();

while(true)
{
i=str.indexOf(' ');
if(i < 0)
break;
s=str.substring(0,i);
str=str.substring(i+1);
if(s.length() > len)
{
len=s.length();
maxs=s;
}
}
if(str.length() > len)
{
len=str.length();
maxs=str;
}

System.out.println("Word with maximum length="+maxs);
System.out.println("And it's length="+len);
}
public static void main(String args[]) throws Exception
{
Word ob=new Word();
ob.take();
}
}

Related Post:  BlueJ Programs on String/Sentence

2 comments:

  1. Sir,
    What does an overloaded version of the String Tokenizer class mean?

    ReplyDelete
    Replies
    1. StringTokenizer class has three overloaded versions of constructor and each version works differently. Please search StringTokenizer in this site and go through the page.

      Delete

Subscribe via email

Enter your email address:

Delivered by FeedBurner