editOut should take a String as input and output a String. You may assume the in
ID: 3726810 • Letter: E
Question
editOut should take a String as input and output a String.
You may assume the input String has properly matched parentheses. The behavior for improperly matched parentheses is up to you, but the method should not crash. The output String should be identical to the input String except that any text inside a pair of matched parentheses is removed, including the parentheses. In addition, if there is a pair of matched parentheses inside the removed text, that text should be retained (though the parentheses should be removed). If there are any matched parentheses inside the retained text, that text should be removed, and so on.
editOut("this is an (unusual (example)) of (editing out and (retaining)) text") should return "this is an example of retaining text"
editOut("this is (another) (example) showing (((((removal))))) -( and )- ((((retention))))") should return "this is showing -- retention"
You are allowed to use the following from the Java API:
class String
length
charAt
class StringBuilder
length
charAt
append
toString
class Character
any method
Explanation / Answer
Code in java:
public class ParenthesisTester {
public boolean matchingParenthesis(String str){
StringBuilder sb=new StringBuilder(str);
int countInp=0;
int countExp=0;
for(int i=0;i<sb.length();i++){
if(sb.indexOf("(")!=-1){
countInp++;
sb.deleteCharAt(sb.indexOf("("));
}
if(sb.indexOf(")")!=-1){
countExp++;
sb.deleteCharAt(sb.indexOf(")"));
}
}
if(countInp==countExp){
return true;
}
else{
return false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
System.out.println("enter a string");
String inp=sc.nextLine();
ParenthesisTester pt=new ParenthesisTester();
if(pt.matchingParenthesis(inp)){
System.out.println("matching");
}
else{
System.out.println("not matching");
}
}
}
output:
1.
enter a string
(“This is a (test (of the ) (matching)) parentheses”)
matching
2.
enter a string
(“the (second closing ) parenthesis) does not match”)
not matching
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.