JAVA Write a Program than using one stack check if one expre

JAVA

Write a Program than using one stack check if one

expression is parenthesis well balanced.

2. Complete this program
public class ex2

{

public static void Print(Stack<Integer> st)

{

// Complete

}
public static void main(String[] args)

{

Stack<Integer> mySt = new LinkedStack();

for(int i=0;i<10;++i) mySt.Push(i);

Print(mySt);

}

}

Solution

I guess you are looking for Expression bancer but Stack of integers can not be used. It should be Stack of Characters.

Sample code:

public static void main (String[] args) throws java.lang.Exception
   {
       // your code goes here
   String ex=\"{[12}\";
   boolean flag=true;
   Stack<Character> st = new Stack<Character>();
for(int i = 0; i < ex.length(); i++) {
char c = ex.charAt(i);
if(c == \'[\' || c == \'(\' || c == \'{\' ) {

st.push(c);
}else if(c == \']\') {
if(st.isEmpty() || st.pop() != \'[\'){flag=false; break;}
}else if(c == \')\') {
if(st.isEmpty() || st.pop() != \'(\'){flag=false; break;}
}else if(c == \'}\') {
if(st.isEmpty() || st.pop() != \'{\'){flag=false; break;}
}

}
  
   if(!flag || !st.isEmpty()){
       System.out.println(\"Expression is not balanced.\");
   }else{
       System.out.println(\"Expression is balanced.\");
   }
  
   }

This code may help

JAVA Write a Program than using one stack check if one expression is parenthesis well balanced. 2. Complete this program public class ex2 { public static void P
JAVA Write a Program than using one stack check if one expression is parenthesis well balanced. 2. Complete this program public class ex2 { public static void P

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site