Please answer 4 and 5 which are linked questions Examples Ex
Please answer 4 and 5 which are linked questions
Examples:
Example 2:
Modify the Match Parenthesis algorithm we discussed in class so that it not only tells whether the parenthesis are matched correctly in an expression, but also identify the position of the first problem in the expression if the parenthesis are not correctly matched. Your algorithm must involve explicit use of stack(s) and should work for at least the test cases below (5 points): 4. i. (a/b(d) your algorithm should show that this expression is correct. ii. a)b your algorithm should show at position 2, \" was presented before having a \"in the expression iii. (a/b(cdefg) your algorithm should show that at position I, a \"\"doesn\'t have matching \"in the expression. iv. (abcdef)g( your algorithm should show that at position 10, a \"\"doesn\'t have matching in the expression. 5. Implement the algorithm you designed in task 4 in C++/Java (Do a screenshot of the execution of the program with at least the above test data, and put the screenshots in your WORD document) (2 points).Solution
Match class
import java.util.Scanner;
import java.util.Stack;
class Data
{
char a;
int i;
Data(char a1,int i1)
{
a=a1;
i=i1;
}
}
public class Matcher {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println(\"Enter expression\");
String expr=sc.nextLine();
boolean ans=checkexpression(expr);
if(ans)
{
System.out.println(\"Correct expression\");
}
else
{
System.out.println(\"error\");
}
sc.close();
}
private static boolean checkexpression(String expr) {
Stack<Data> str=new Stack<Data>();
char[] c=expr.toCharArray();
Data d;
//logic for paraenthesis check
for(int i=0;i<c.length;i++)
{
if(c[i]==\'(\'||c[i]==\'{\'||c[i]==\'[\')
{
str.push(new Data(c[i],i));
}
else if(!str.isEmpty()&&c[i]==\')\'||c[i]==\'}\'||c[i]==\']\')
{
d=str.peek();
if(d.a==\'(\'&&c[i]==\')\'||d.a==\'{\'&&c[i]==\'}\'||d.a==\'[\'&&c[i]==\']\')
{
str.pop();
}
else
{
System.out.println(\"Paranthesis at \"+(d.i+1)+ \" \"+ d.a+\" does not matches the \"+ c[i]);
return false;
}
}
else if(str.isEmpty()&&c[i]==\')\'||c[i]==\'}\'||c[i]==\']\')
{
System.out.println(\"at position \"+ (i+1)+ \"showing closing parantheiss before opening paranthesis\");
return false;
}
}
if(str.isEmpty())
return true;
else
{
d=str.peek();
System.out.println(\"Paranthesis at \"+ (d.i+1) +\" \"+d.a+\" do not have closing paraenthesis\");
return false;
}
}
}
Output:
1.
Enter expression
(a/b(d))
Correct expression
2.
Enter expression
a)b(
at position 2showing closing parantheiss before opening paranthesis
error
3.
Enter expression
(a/b(cdef)
Paranthesis at 1 ( do not have closing paraenthesis
error
4.
Enter expression
(abcde)(
Paranthesis at 8 ( do not have closing paraenthesis
error

