Computer Science, asked by Anonymous, 5 months ago

WAP in java to enter any sentence and display the longest and shortest word.
Use String Tokenizers.

Answers

Answered by Oreki
2

\text\boxed{Program}

\texttt{import java.util.Scanner;}

\texttt{import java.util.StringTokenizer;}

\texttt{public class LongestShortestWord \{}

   \texttt{public static void main(String[ ] args) \{}

       \texttt{String longest = '''', shortest = ''1''.repeat(50);}

       \texttt{System.out.print("Enter a sentence - ");}

       \texttt{for (StringTokenizer st = new StringTokenizer(}

               \texttt{new Scanner(System.in).nextLine( )); st.hasMoreTokens( ); ) \{}

           \texttt{String word = st.nextToken( );}

           \texttt{longest = (word.length() > longest.length()) ?\ word :\ longest;}

           \texttt{shortest\ =\ (word.length()\ <\ shortest.length()) ?\ word :\ shortest;}

       \texttt{\}}

       \texttt{System.out.println("Longest word - " + longest);}

       \texttt{System.out.println("Shortest word - " + shortest);}

   \texttt{\}}

\texttt{\}}

\text{StringTokenizer\:class}

\textsf{\quad It allows us to break a string into tokens or simply put, into words separated by space.}\textsf{\quad It is an easy way to break a String.}

  • boolean hasMoreTokens( ) - checks if there are any further tokens/words accessible.
  • String nextToken( ) - returns the succeeding token/word from the String passed.

\text{Algorithm}

  • Accepting the sentence using the Scanner class.
  • Processing the sentence as specified by the question using the StringTokenizer class.
  • Finding smallest and longest words by comparing the length of each word.
  • Displaying the results.
Attachments:
Similar questions