Write a program to accept a sentence which may be terminated by either ‘.’ ‘?’ or ‘!’ only. Any other character may be ignored. The words may be separated by more than one blank space and are in UPPER CASE.
Perform the following tasks:
(a) Accept the sentence and reduce all the extra blank space between two words to a single blank space.
(b) Accept a word from the user which is part of the sentence along with its position number and delete the word and display the sentence.
Test your program with the sample data and some random data:
Example 1
INPUT:
A MORNING WALK IS A IS BLESSING FOR THE WHOLE DAY.
WORD TO BE DELETED:
IS
WORD POSITION IN THE SENTENCE:
6
OUTPUT:
A MORNING WALK IS A BLESSING FOR THE WHOLE DAY.
Example 2
INPUT:
AS YOU SOW, SO SO YOU REAP.
WORD TO BE DELETED: SO
WORD POSITION IN THE SENTENCE:
4
OUTPUT:
AS YOU SOW, SO YOU REAP.
import java.util.*;
class RemoveWord
{
String sent;
int len;
Scanner sc=new Scanner(System.in);
public RemoveWord()
{
sent="A MORNING WALK IS A IS BLESSING FOR THE WHOLE DAY.";
len=sent.length();
}
void accept()
{
System.out.print("Enter a sentence : ");
sent = sc.nextLine();
sent = sent.toUpperCase();
len = sent.length();
}
public void delWord()
{
char last = sent.charAt(len-1); // Extracting the last character
/* Checking whether the sentence ends with '.' or '?' or not */
if(last != '.' && last != '?' && last != '!')
{
System.out.println("Invalid Input. End a sentence with either '.', '?' or '!' only");
}
else
{
StringTokenizer str = new StringTokenizer(sent," . ? ! ");
int c = str.countTokens();
System.out.println("Sentence is : "+sent);
System.out.println("No of words : "+c);
String w="",ans = "";
System.out.print("Enter the word to delete : ");
String del = sc.next();
System.out.print("Enter the word position is the sentence : ");
int x = sc.nextInt();
if(x<1 || x > c) // Checking whether integer inputted is acceptable or not
{
System.out.println("Sorry! The word position entered is out of range");
}
else
{
for(int i=1; i<=c; i++)
{
w = str.nextToken();
/* Skipping if the word to delete and the position matches */
if(w.equals(del)==true && i == x)
continue;
ans = ans + w + " ";
}
System.out.print("Output : "+ans.trim()+last);
}
}
}
public static void main (String args[])
{
RemoveWord ob = new RemoveWord();
ob.delWord();
}
}