Hit the nail on the head program in Java
24---Write a program to read a sentence which terminates with a full stop(.).The words are to
be sperated by a single blank space and are in lower case.Arrange the words in ascending
order according to the length of the words.If 2 words are of same length then the word
occuring first in the input sentence should come first.For for input and output the
sentence must begin with upper case.
SAMPLE INPUT : Hit the nail on the head.
SAMPLE OUTPUT : On hit the the nail head.
import java.util.*;
class LengthWise{
public static void main()
{Scanner sc=new Scanner(System.in);
String s,t,x="",y;
int i,l;
System.out.println("Enter a String");
s=sc.nextLine();
l=s.length();//finding length
if(Character.toUpperCase(s.charAt(0))!=s.charAt(0)||s.charAt(l-1)!='.')
System.out.println("The Sentence will start with a capital letter and end with a .");
else{
s=s.substring(0,l-1).toLowerCase();
l=l-1;
for(i=1;i<=l;i++){
Scanner a=new Scanner(s);
while(a.hasNext()){
t=a.next();
if(t.length()==i)
x=x+t+" ";//creating arranged string
}
}
x=Character.toUpperCase(x.charAt(0))+x.substring(1,x.length()-1)+".";
System.out.println("ARRANGED INCREASINGLY LENGTH WISE\n"+x);
}
}//end of main
}//end of class
OUTPUT---
Enter a String
Hit the nail on the head.
ARRANGED INCREASINGLY LENGTH WISE
On hit the the nail head.
be sperated by a single blank space and are in lower case.Arrange the words in ascending
order according to the length of the words.If 2 words are of same length then the word
occuring first in the input sentence should come first.For for input and output the
sentence must begin with upper case.
SAMPLE INPUT : Hit the nail on the head.
SAMPLE OUTPUT : On hit the the nail head.
import java.util.*;
class LengthWise{
public static void main()
{Scanner sc=new Scanner(System.in);
String s,t,x="",y;
int i,l;
System.out.println("Enter a String");
s=sc.nextLine();
l=s.length();//finding length
if(Character.toUpperCase(s.charAt(0))!=s.charAt(0)||s.charAt(l-1)!='.')
System.out.println("The Sentence will start with a capital letter and end with a .");
else{
s=s.substring(0,l-1).toLowerCase();
l=l-1;
for(i=1;i<=l;i++){
Scanner a=new Scanner(s);
while(a.hasNext()){
t=a.next();
if(t.length()==i)
x=x+t+" ";//creating arranged string
}
}
x=Character.toUpperCase(x.charAt(0))+x.substring(1,x.length()-1)+".";
System.out.println("ARRANGED INCREASINGLY LENGTH WISE\n"+x);
}
}//end of main
}//end of class
OUTPUT---
Enter a String
Hit the nail on the head.
ARRANGED INCREASINGLY LENGTH WISE
On hit the the nail head.
Comments
Post a Comment