Write a Java program to implement stack by creating user defined push method for
ID: 3832759 • Letter: W
Question
Write a Java program to implement stack by creating user defined push method for entering { and (, and pop method for retrieving { and ( from the stack. This program is for expression evaluation and syntax parsing. This program should display appropriate error message if input expression has wrong.
This is Code Example:
int howMany=5;
String[] myStatement= new String[howMany];
char[] myStack= new char[40];
int stackTop;
// Main method
myStatement[0]="( 1 + 3) * { 2 - 1 )";
...
myStatement[4]="( 1 + 3) * ((2 - 1 )";
for (int i=0;i stackTop=-1;
for (int j=0;j char c= myStatement[i].charAt(j);
if (c=='{' || c=='(') {
myPush(c);
}
if (c=='}') {
char popedChar=myPop();
// check correct or not
}
if (c==')') {
char popedChar=myPop();
// check correct or not
}
}
public static void myPush(char c){
// push operation
}
public static char myPop(){
// pop operation
return c;
}
The output is
( 1 + 3) * { 2 - 1 )
^ error: '}' expected
Explanation / Answer
Hi,
Basically this question is for determining the balanced paranthesis inside string .
So i am writing the method in which you can pass the myStatement[] array and get the desired result
/**
In case the expression is balanced then this method returns null else it returns the parenthesis which is required to fix error
**/
private static String isExpressionBalanced(String input){
Stack<String> stack = new Stack<String>();
String isBalanced = null;
for(int i=0; i < input.length(); i++){
String str = ""+input.charAt(i); //store characters as String
//if opening bracket then push into stack
if(str.equals("(") || str.equals("[") || str.equals("{")){
stack.push(str);
}
//if closing bracket, pop bracket and compare if its a pair
if(str.equals(")") || str.equals("]") || str.equals("}")){
//if stack becomes empty in between then also its not balanced
if(stack.isEmpty()){
return str;
}
String opening = stack.peek();
if(str.equals(")") && opening.equals("(")){
stack.pop();
}
if(str.equals("]") && opening.equals("[")){
stack.pop();
}
if(str.equals("}") && opening.equals("{")){
stack.pop();
}
}
}
//if stack is empty at end, then its balanced
if(input.length() > 0 && stack.isEmpty()){
isBalanced = null;
}
return isBalanced;
}
/**
main method in which the string array will be passed
**/
public static void checkExpression(String[] myStatement) {
for ( String stmt : myStatement) {
if (isExpressionBalanced(stmt) != null) {
System.out.println("The expression: " + stmt + " is unbalanced by paranthesis: " + isExpressionBalanced(stmt))
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.