Find the Longest and the Shortest Words in a Sentence in Java
Write a Java Program to input a sentence and find and display the longest and the shortest words from that sentence along with their lengths.
import java.util.Scanner;
class Find{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Sentence: ");
String s = in.nextLine().trim().toUpperCase();
char last = s.charAt(s.length() - 1);
if(".!?".indexOf(last) == -1){
System.out.println("Invalid sentence!");
return;
}
String word = new String();
String longest = new String();
String shortest = new String(s);
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(Character.isLetterOrDigit(ch))
word += ch;
else{
if(longest.length() < word.length())
longest = new String(word);
if(shortest.length() > word.length())
shortest = new String(word);
word = new String();
}
}
System.out.println("Longest word: " + longest);
System.out.println("Length of the longest word: " + longest.length());
System.out.println("Shortest word: " + shortest);
System.out.println("Length of the smallest word: " + shortest.length());
}
}
class Find{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Sentence: ");
String s = in.nextLine().trim().toUpperCase();
char last = s.charAt(s.length() - 1);
if(".!?".indexOf(last) == -1){
System.out.println("Invalid sentence!");
return;
}
String word = new String();
String longest = new String();
String shortest = new String(s);
for(int i = 0; i < s.length(); i++){
char ch = s.charAt(i);
if(Character.isLetterOrDigit(ch))
word += ch;
else{
if(longest.length() < word.length())
longest = new String(word);
if(shortest.length() > word.length())
shortest = new String(word);
word = new String();
}
}
System.out.println("Longest word: " + longest);
System.out.println("Length of the longest word: " + longest.length());
System.out.println("Shortest word: " + shortest);
System.out.println("Length of the smallest word: " + shortest.length());
}
}
Comments
Post a Comment