Page 419 - Computer science 868 Class 12
P. 419
Program 9 A class called Longword is defined to print the longest word in a sentence. Assume that the
sentence has a unique longest word and that the word separators are space and full stop
only. The class description is given below
Data Members
String sen,wrd : To store sentence and longest word
Member Methods
void read() : Accept sentence
String findlong(String s) : Using recursive technique find the longest word in the
sentence
void show() : Calls findlong (String) and prints the longest word
static void main() : Creates object and calls other methods
1 import java.util.*;
2 class Longword
3 { String sen,wrd;
4 void read()
5 { Scanner sc=new Scanner(System.in);
6 System.out.println("Enter sentence ending with fullstop");
7 sen=sc.nextLine();
8 int l=sen.length();
9 sen=" "+sen.substring(0,l-1)+" "; //Sentence starting and ending with space
10 wrd="";
11 }
12 String findlong(String s)
13 { int p1,p2;
14 String s1;
15 if(s.equals(" "))
16 return(wrd);
17 else // finding the position of space in front and back of each word
18 { p1=s.indexOf(' ');
19 p2=s.indexOf(' ',p1+1);
20 s1=s.substring(p1+1,p2); // extracting each word and printing it
21 System.out.println(s1);
22 if(s1.length()>wrd.length()) // finding longest word
23 wrd=s1;
24 return findlong(s.substring(p2)); // recursive case
417
Recursion 417

