Writa a program to accept a sentence which may be terminated by either '.' or ? or '!' only. Any other character may be ignored. The words may be seperated by one or more than one blank spaces and in UPPER CASE.
import java.util.*;
public class Upper {
String sent = "";
int wordIndex = -1;
String wordToInsert = "";
String outSent = ""; // output sentence
void input() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence: ");
sent = sc.nextLine().toUpperCase();
// Checking if the sentence only ends in '.' or '?' or '!'
// using demorgan's law to obtain the boolean expression below
if (!sent.endsWith(".") && !sent.endsWith("?") && !sent.endsWith("!")) {
System.out.println("Invalid sentence");
System.exit(-1);
}
System.out.print("Enter the word to insert: ");
wordToInsert = sc.next().toUpperCase();
System.out.print("Enter the word position in the sentence: ");
wordIndex = sc.nextInt() - 1;
sc.close();
}
void display() {
StringTokenizer tokens = new StringTokenizer(sent, " ");
String res = "";
for (int i = 0; tokens.hasMoreTokens(); i++) {
String word = tokens.nextToken();
if (i == wordIndex)
res += wordToInsert + " ";
res += word + " ";
}
outSent = res;
System.out.println("The new sentence is:\n" + outSent);
}
public static void main(String[] args) {
Upper obj = new Upper();
obj.input();
obj.display();
}
}
Name | Type | Description |
---|---|---|
global | ||
sent | String | to store the sentence |
wordToInsert | String | to store the word to be inserted |
wordIndex | int | to store the index of the word to be inserted |
outSent | String | to store the output sentence |
void input() | ||
sc | Scanner | to take user input |
void display() | ||
tokens | StringTokenizer | to tokenize the sentence to extract words |
res | String | to store the output sentence |
i | int | to store the index of the word (counter variable) |