Write a JAVA program that allows the user to enter a mathematical expression to
ID: 3847564 • Letter: W
Question
Write a JAVA program that allows the user to enter a mathematical expression to check its validation. Implement the Parenthesis Matching Algorithm discussed in class using linked-list Stack to be able to check if a user's mathematical expression is valid or not. You can use the Stack code listed under the Course meterials to start your implementation. You might need to make some adjustments to the code, add the paranthesisMatching method and test it in the Tester class. For example: (3 * 21 + 5) is valid, while (4 + 52 * [3 + 2]} is not valid.Explanation / Answer
import java.util.*;
import java.util.Scanner;
class Tester
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
Tester test = new Tester();
System.out.println(" Parenthesis Balance Tester");
System.out.println(" Enter Expression: ");
String expr = scan.next();
int l = expr.length();
System.out.println(" Expression is " +ParenthesisMatching(expr));
}
public static String ParenthesisMatching(String expr)
{
Stack<Integer> stack = new Stack<Integer>();
int l = 0;
for(int i=0; i<l; i++)
{
char ch = expr.charAt(i);
if(ch == '(')
{
stack.push(i);
}
if(ch == ')')
{
if(stack.isEmpty())
{
return "Invalid";
}
if(ch == ')')
{
stack.pop();
}
else
return "Invalid";
}
}
if(stack.isEmpty())
return "Valid";
else
return "InValid";
}
}
OUTPUT
Parenthesis Balance Tester
Enter Expression:(3*21+5)
Expression is Valid
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.