Write a complete program that reads some text from the user (until the Enter key
ID: 3815713 • Letter: W
Question
Write a complete program that reads some text from the user (until the Enter key is pressed). The program should display the total number of words entered, length of the shortest word entered, and a list of the shortest words. If there are multiple shortest words, display all of them. You may assume that no punctuation is entered, and there is exactly one space between each pair of words and there is no leading space at the beginning and no trail space at the end. EnCer words: This is an exam in the computer science department 9 words were entered Shortest word length; 2 Shortest word (s): is an in import java.util.Scanner; public class GetWordlnfo {public static void main(String [] args) {Explanation / Answer
Hi,
Please use below code for shortest word-
import java.util.Scanner;
public class HelloWorld {
static int i,c=0,res;
static int wordcount(String s)
{
char ch[]= new char[s.length()]; //in string especially we have to mention the () after length
for(i=0;i<s.length();i++)
{
ch[i]= s.charAt(i);
if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )
c++;
}
return c;
}
void shortAndLongWord(String str)
{
if (str == null)
return;
String sw="",lw="";
int s=str.length(),l=0;
String words[]=str.split(" ");
for(String word:words)
{
if(word.length()<s)
{
sw=word;
s = word.length();
}
if(word.length()>l)
{
lw=word;
l = word.length();
}
if(word.length()==sw.length())
{
sw=word;
}
}
for(String word:words)
{
if(word.length()==sw.length())
System.out.println("SHORTEST WORD : "+word);
}
}
public static void main(String[] args) {
Scanner scr=new Scanner(System.in);
HelloWorld obj=new HelloWorld();
System.out.printf("Enter a line to get shortest and longest word:");
String str=scr.nextLine();
str+=" ";
obj.shortAndLongWord(str);
System.out.print("Your sentence has " + obj.wordcount(str) + " words.");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.