public class ISC2021SpecimenQuestion2{
public static void main(String[] args) throws IOException{
String Sentence;
boolean lowerflag;
boolean spaceflag;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
System.out.println("Enter the sentence:");
Sentence=br.readLine();
if( Sentence.charAt(Sentence.length()-1)!= '.'
&& Sentence.charAt(Sentence.length()-1)!= '?'
&& Sentence.charAt(Sentence.length()-1)!= '!') //end of if
System.out.println("INVALID INPUT:,TRY AGAIN");
lowerflag = true;
spaceflag = true;
// checking for lowercase
for(int i = 0; i<Sentence.length();i++)
if(!Character.isLowerCase(Sentence.charAt(i)) && Character.isLetter(Sentence.charAt(i))) {
lowerflag = false;
System.out.println("Must be in lower case,TRY AGAIN");
break;
}
//checking for more than one space
for(int i = 0; i<Sentence.length()-1;i++)
if(Sentence.charAt(i) ==' ')
if(Sentence.charAt(i+1) == ' ') {
spaceflag = false;
System.out.println("Words must be seperated by a single space");
break;
}
} while((Sentence.charAt(Sentence.length()-1)!= '.'
&& Sentence.charAt(Sentence.length()-1)!= '?'
&& Sentence.charAt(Sentence.length()-1)!= '!')
|| lowerflag==false || !spaceflag); //end of do-while
SenetenceSort obj = new SenetenceSort(Sentence);
System.out.println("OUTPUT:");
char c = Character.toUpperCase(Sentence.charAt(0));
Sentence = String.valueOf(c) + Sentence.substring(1,Sentence.length() );
System.out.println(Sentence);
obj.wordExtractor();
obj.sortWords();
obj.display();
br.close();
}
}
class SenetenceSort{
public void display() {
char c = Character.toUpperCase(word_Storage[0].charAt(0));
word_Storage[0] = String.valueOf(c) + word_Storage[0].substring(1,word_Storage[0].length() );
for(int i = 0;i<word_counter;i++) {
if(i==word_counter-1)
System.out.print(word_Storage[i]+msg.charAt(msg.length()-1));
else
System.out.print(word_Storage[i]+" ");
}
}
public void sortWords() {
String temp;
int i,j;
for(i = 0;i<word_counter-1; i++)
for (j = 0; j < word_counter-i-1; j++)
// sorting length wise - only if lengths are different ( no equal sign is placed)
if (word_Storage[j].length() > word_Storage[j+1].length()) {
temp=word_Storage[j+1];
word_Storage[j+1]=word_Storage[j];
word_Storage[j]=temp;
}
}
public void wordExtractor() {
int i;
//counting the number of words
for(i=0;i<msg.length();i++)
if(msg.charAt(i)== ' ')
word_counter++;
word_counter +=1; // In any sentence, number of words is 1 greater than the number of spaces
word_Storage = new String[word_counter];
int k = 0;
//extracting words
for(i=0;i<msg.length();i++) {
word_Storage[k]="";
while(msg.charAt(i) != ' ' && i < msg.length()-1) {
word_Storage[k] +=msg.charAt(i);
i++;
}
k++;
} // end of i-loop
}
SenetenceSort(String Sentence){
this.msg=Sentence;
this.word_counter=0;
}
private String msg;
private int word_counter;
private String[] word_Storage;
}
No comments:
Post a Comment