Program to accept a sentence and remove all parentheses contents. In case the parentheses are only opened or only closed then show appropriate error message.
Example 1: “The Sun rises (at noon(4pm)) from East”. The program should remove all parentheses contents including the parentheses giving us an output “The Sun rises from East”.
Example 2: “The Sun rises (at noon (4pm) from East”. Since all the parentheses are not closed the program should output an error message.
Java
import java.util.*;
public class RemParentheses
{
public static void main(String args[])
{
String str="",nstr="";
int l=0,count=0;
char ch=' ';
Scanner sc=new Scanner(System.in);
System.out.print("Enter a string: ");
str=sc.nextLine();
str=str.trim();
l=str.length();
for(int i=0;i<l;i++)
{
ch=str.charAt(i);
if(ch=='(')
{
nstr=nstr.trim();
count++;
}
else if(ch==')')
{
count--;
}
else if(count==0)
{
nstr=nstr+ch;
}
}
if(count==0)
{
System.out.println("New string: "+nstr);
}
else
{
System.out.println("Error!! Invalid string");
}
}
}Java