In: Computer Science
Your program should take a string representing a sentence in English and format it properly. The input sentence may have any or all of the following errors:
Random letters may be capitalized.
The sentence may not end with a proper punctuation mark (period, question mark, or exclamation point).
There may be spaces at the beginning or end, or more than one space between words.
Format the sentence to fit the following rules:
The first letter of the first word should be capitalized.
The word "I" should be capitalized.
All other letters in all words should be in lowercase.
The sentence should end with a punctuation mark. If the original sentence did not end with a punctuation mark, add a period. (If the original sentence ended with more than one punctuation mark, it is not your responsibility to detect or fix this. However, you should not cause this problem yourself by adding a period if the sentence already ends with a punctuation mark.)
There should be no spaces at the beginning or end of the sentence.
There should be only a single space between words.
Example:
java Sentence corRect pUNCtuation is hard, i tHINk RESULT: Correct punctuation is hard, I think.
import java.util.Arrays;
import java.util.Scanner;
public class SentenceChecker {
public static void main(String[] args) {
boolean punctuationCheck = false;
boolean firstCharecterCheck = false;
Scanner input = new Scanner(System.in);
System.out.println("Enter The Sentence");
String sentence = input.nextLine();
String[] words = sentence.split("\\s+");
words[0] = words[0].trim();
String lastWord = words[words.length - 1];
lastWord = lastWord.trim();
Character lastChar = lastWord.charAt(lastWord.length() - 1);
if (lastChar != '.' && lastChar != '?' && lastChar != '!') {
lastChar = '.';
punctuationCheck = true;
}
if (punctuationCheck)
lastWord = lastWord + lastChar;
StringBuffer correctedSententce = new StringBuffer();
String firstWord = words[0];
Character firstChar = firstWord.charAt(0);
if (!Character.isUpperCase(firstChar)) {
firstWord = Character.toUpperCase(firstChar) + firstWord.toLowerCase().substring(1, firstWord.length());
}
correctedSententce.append(firstWord);
for (int i = 1; i < words.length - 1; i++) {
String string = words[i];
if (string.equals("i")) {
string = "I";
correctedSententce.append(" " + string);
continue;
}
firstChar = string.charAt(0);
if (Character.isUpperCase(firstChar)) {
firstCharecterCheck = true;
}
if (firstCharecterCheck) {
string = string.toLowerCase();
string = firstChar + string.substring(1, string.length());
} else {
string = string.toLowerCase();
}
correctedSententce.append(" " + string);
}
lastWord = lastWord.toLowerCase();
correctedSententce.append(" " + lastWord);
System.out.println(correctedSententce);
}
}