Consider mathematical expressions such as the following, (A * (B + C)) *(D - E)
ID: 3690024 • Letter: C
Question
Consider mathematical expressions such as the following,
(A * (B + C)) *(D - E)
A compiler can verify such expression is a matched form. However, the following two forms are unmatched.
(A * B) + )C(
(A*(B+C)
Write a program to check whether ‘(‘ and ‘)’ match in an expression. Use stack. Do not check brackets or curly braces. You can either use standard Stack in Java or the Stack in this course .
For the input string str, how do you determine if it is a ‘(‘ or ‘)’?
You can either use if (str.charAt(i) == 40) or use if (str.charAt(i) == ‘(‘) to check ‘(‘. The same to check ‘(‘.
Partial program is given as follows:
import java.util.*;
public class CheckMatched
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter an expression:");
String expression = in.nextLine();
if (isMatched(expression))
System.out.println("The expression is matched");
else
System.out.println("The expression is unmatched");
}
private static boolean isMatched(String expression)
{
LinkedListStack stack = new LinkedListStack();
int length = expression.length();
for (int i = 0; i < expression.length(); i++)
{
if (expression.charAt(i) == '(')
{
// add statement
}
else if (expression.charAt(i) == ')')
{
//add statements
}
}
// return something
}
}
Explanation / Answer
private static boolean isMatched (String expression)
{
LinkedListStack stack= new LinkedListStack();
int length=expression.length();
for(int i=0;i<length;i++)
{
if(expression.charAt(i)=='(' )
{
stack.push(1);
}
else if( expression.charAt(i)==')' )
stack.pop(1);
}
if(stack.empty())
return true;
return false;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.