In: Computer Science
Write a Java program which takes a String representing an arithmetic expression as an input and displays whether or not the expression is balanced. If the expression is not balanced (i.e. the wrong # of parentheses or in the wrong order) it will display an error message. For Example: Input an expression: ( ( 2 + 4 ) * 2 ) Expression is balanced Input an expression: ( 5 * 7 – 6 ) ) Error: Expression is not balanced.... Implement a stack calculator using both a numbers and operations stack. Be sure to check that the expression is balanced before running it through the calculator.
import java.util.*;
import java.io.*;
public class Main
{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in); //System.in is a standard input stream.
System.out.print("Enter arthematic expression: ");
String str= sc.nextLine(); //reads string.
String result=check(str);
System.out.print(str+" is "+result);
}
public static String check(String expr)
{
if (expr.isEmpty())
return "Balanced";
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < expr.length(); i++)
{
char current = expr.charAt(i);
if (current == '{' || current == '(' || current == '[')
{
stack.push(current);
}
if (current == '}' || current == ')' || current == ']')
{
if (stack.isEmpty())
return "Not Balanced";
char last = stack.peek();
if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
stack.pop();
else
return "Not Balanced";
}
}
return stack.isEmpty()?"Balanced":"Not Balanced";
}
}