Operator changed to int during infix to postfix conversion - java

private DSAQueue parseInfixToPostfix(String equation) {
String result = "";
char operator = ' ';
DSAStack stack = new DSAStack();
DSAQueue queue = new DSACircular();
for (int i = 0; i < equation.length(); i++) {
char c = equation.charAt(i);
if (Character.isLetterOrDigit(c)) {
result += c;
}
else if (c == '(') {
stack.push(c);
}
else if (c == ')') {
while (!stack.isEmpty() && stack.top() != '(') {
result += stack.pop();
}
if (!stack.isEmpty() && stack.top() != '(') {
result = "Invalid expression";
}
else {
stack.pop();
}
}
else { //when meets operator
while (!stack.isEmpty() && (precedenceOf(c) <= precedenceOf((char) stack.top()))) {
if (stack.top() == '(') {
result = "Invalid expression";
}
result += stack.pop();
}
stack.push(c);
}
}
while (!stack.isEmpty()) {
if (stack.top() == '(') {
result = "Invalid";
}
result += stack.pop();
}
queue.enqueue(result);
return queue;
}
Above is my code for converting infix to postfix. The example i used is "4+2" and what i got is:
Pushed: 43
Popped: 43
Enqueued: 4243
i dont know why it automatically converted "+" to 43, but i want to store the operator as the operator like "+" in the queue. Is it possible? Or is there an error? because i cant find out what the error is. thank you

Related

Recursive method to evaluate expressions just work when method is called once

I'm writing a code to valuate math expressions. The code just works when I call the methode once. But I have more than one expression to evaluate and it just break when I call the method more than two times. I get the following error:
-2
Exception in thread "main" java.util.EmptyStackException
at java.util.Stack.peek(Stack.java:102)
at java.util.Stack.pop(Stack.java:84)
at Evaluate.parse(Evaluate.java:58)
at Evaluate.main(Evaluate.java:11)
I see that the code gives me the expected result (the -2) but what I'm doing wrong regarding the methode that gives me this error
My code:
public class Evaluate {
static Stack<Character> ops = new Stack<Character>();
static Stack<Integer> vals = new Stack<Integer>();
static int i = 0;
public static void main(String[] args) {
System.out.println(parse("(4-(7-1))"));
System.out.println(parse("8"));
System.out.println(parse("((1+1)*(2*2))"));
System.out.print("\n");
System.out.println(parse("(6/(3/2))"));
}
private static int parse(String expression) {
char[] tokens = expression.toCharArray();
while (tokens.length > i) {
char s = tokens[i];
if (s == '(') {
ops.push(tokens[i]);
} else if (s == '+' || s == '-' || s == '*' || s == '/') {
while (!ops.empty() && hasPrecedence(tokens[i], ops.peek()))
vals.push(applyOp(ops.pop(), vals.pop(), vals.pop()));
ops.push(s);
} else if (s == ')') {
char op = ops.pop();
int v = vals.pop();
while (ops.peek() != '(')
vals.push(applyOp(ops.pop(), vals.pop(), vals.pop()));
ops.pop();
if (op == '+') {
v = vals.pop() + v;
} else if (op == '-') {
v = vals.pop() - v;
} else if (op == '*') {
v = vals.pop() * v;
} else if (op == '/') {
v = vals.pop() / v;
}
vals.push(v);
} else {
vals.push(Character.getNumericValue(s));
}
i++;
}
while (!ops.empty())
vals.push(applyOp(ops.pop(), vals.pop(), vals.pop()));
return vals.pop();
}
public static boolean hasPrecedence(char op1, char op2) {
if (op2 == '(' || op2 == ')')
return false;
if ((op1 == '*' || op1 == '/') && (op2 == '+' || op2 == '-'))
return false;
else
return true;
}
// A utility method to apply an
// operator 'op' on operands 'a'
// and 'b'. Return the result.
public static int applyOp(char op, int b, int a) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new UnsupportedOperationException("Cannot divide by zero");
return a / b;
}
return 0;
}

Fails for the testcase "([}}])" to validate expression(balancing parenthesis problem) which is coded in java

This code is written when I was trying to solve the problem on Leet code(the link to the problem is given below), which performs the balancing parenthesis but failing for the condition ([}}]) could anyone help me.
Thank you.
problem link---> https://leetcode.com/problems/valid-parentheses/
import java.util.*;
public class expressionValidation
{
public static void main(String[] args)
{
try (Scanner sc = new Scanner(System.in))/*trying to avoid any kind of exceptions*/
{
String str = sc.nextLine();
String exp = "";/*new string to modify the given expression*/
int l = str.length();
for(int i=0;i<l;i++)
{
if(str.charAt(i)=='{'||str.charAt(i)=='('||str.charAt(i)=='['||str.charAt(i)=='}'||str.charAt(i)==']'||str.charAt(i)==')')
{
exp+=str.substring(i,i+1);/*newly modified string afterstrong text removing everything except brackets'(' '[' '{' ' }' ']' ')'*/
}
}
stack ob = new stack();
System.out.println(ob.isValid(exp)?"Balanced":"NOT Balanced");
}
}
}
## The following is the stack class
class stack
{
boolean isValid(String exp)
{
int l =exp.length();
if(l%2!=0)
return false;
Stack<Character> st = new Stack<Character>();
for(int i=0;i<l;i++)
{
if(exp.charAt(i)=='{' ||exp.charAt(i)=='(' ||exp.charAt(i)=='[' ) {
st.push(exp.charAt(i));
}
else if(exp.charAt(i)=='}' && !(st.isEmpty()) && st.peek()=='{') {
st.pop();
}
else if(exp.charAt(i)==')' && !(st.isEmpty()) && st.peek()=='(') {
st.pop();
}
else if(exp.charAt(i)==']' && !(st.isEmpty()) && st.peek()=='[') {
st.pop();
}
String str = st.toString();
System.out.println(str);
}
return st.isEmpty();
}
}
My LeetCode submission :-
public boolean isValid(String s) {
Stack<Character> sc = new Stack<>();
for(int i =0;i<s.length();i++){
char ch = s.charAt(i);
if(ch == '(' || ch == '{' || ch == '['){
sc.push(ch);
}else if(ch == ')'){
if(!sc.isEmpty() && sc.peek() == '('){
sc.pop();
}else{
return false;
}
}else if(ch == '}'){
if(!sc.isEmpty() && sc.peek() == '{'){
sc.pop();
}else{
return false;
}
}else if(ch == ']'){
if(!sc.isEmpty() && sc.peek() == '['){
sc.pop();
}else{
return false;
}
}
}
if(sc.isEmpty()){
return true;
}else{
return false;
}
}
Try this.
boolean isValid(String s) {
int max = s.length(), index = 0;
char[] stack = new char[max];
for (int i = 0; i < max; ++i) {
char c = s.charAt(i);
switch (c) {
case '(': stack[index++] = ')'; break;
case '[': stack[index++] = ']'; break;
case '{': stack[index++] = '}'; break;
default:
if (index <= 0 || stack[--index] != c)
return false;
break;
}
}
return index == 0;
}
When you encounter } and the following condition fails
else if(exp.charAt(i)=='}' && !(st.isEmpty()) && st.peek()=='{') {
you should already produce an error, but you just silently ignore the incoming } and continue the iteration. So all unpaired closing parenthesis/brackets are just silently removed from your input. Instead of ([}}]) you analyze ([]) which is a balanced string, so you get no error.
Same is true for other closing characters as well.

What are the cases to be considered while parsing a mathematical expression(brackets)? [duplicate]

For example if the parenthesis/brackets is matching in the following:
({})
(()){}()
()
and so on but if the parenthesis/brackets is not matching it should return false, eg:
{}
({}(
){})
(()
and so on. Can you please check this code?
public static boolean isParenthesisMatch(String str) {
Stack<Character> stack = new Stack<Character>();
char c;
for(int i=0; i < str.length(); i++) {
c = str.charAt(i);
if(c == '{')
return false;
if(c == '(')
stack.push(c);
if(c == '{') {
stack.push(c);
if(c == '}')
if(stack.empty())
return false;
else if(stack.peek() == '{')
stack.pop();
}
else if(c == ')')
if(stack.empty())
return false;
else if(stack.peek() == '(')
stack.pop();
else
return false;
}
return stack.empty();
}
public static void main(String[] args) {
String str = "({})";
System.out.println(Weekly12.parenthesisOtherMatching(str));
}
Your code has some confusion in its handling of the '{' and '}' characters. It should be entirely parallel to how you handle '(' and ')'.
This code, modified slightly from yours, seems to work properly:
public static boolean isParenthesisMatch(String str) {
if (str.charAt(0) == '{')
return false;
Stack<Character> stack = new Stack<Character>();
char c;
for(int i=0; i < str.length(); i++) {
c = str.charAt(i);
if(c == '(')
stack.push(c);
else if(c == '{')
stack.push(c);
else if(c == ')')
if(stack.empty())
return false;
else if(stack.peek() == '(')
stack.pop();
else
return false;
else if(c == '}')
if(stack.empty())
return false;
else if(stack.peek() == '{')
stack.pop();
else
return false;
}
return stack.empty();
}
This code is easier to understand:
public static boolean CheckParentesis(String str)
{
if (str.isEmpty())
return true;
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < str.length(); i++)
{
char current = str.charAt(i);
if (current == '{' || current == '(' || current == '[')
{
stack.push(current);
}
if (current == '}' || current == ')' || current == ']')
{
if (stack.isEmpty())
return false;
char last = stack.peek();
if (current == '}' && last == '{' || current == ')' && last == '(' || current == ']' && last == '[')
stack.pop();
else
return false;
}
}
return stack.isEmpty();
}
public static boolean isValidExpression(String expression) {
Map<Character, Character> openClosePair = new HashMap<Character, Character>();
openClosePair.put(')', '(');
openClosePair.put('}', '{');
openClosePair.put(']', '[');
Stack<Character> stack = new Stack<Character>();
for(char ch : expression.toCharArray()) {
if(openClosePair.containsKey(ch)) {
if(stack.pop() != openClosePair.get(ch)) {
return false;
}
} else if(openClosePair.values().contains(ch)) {
stack.push(ch);
}
}
return stack.isEmpty();
}
The algorithm:
scan the string,pushing to a stack for every '(' found in the string
if char ')' scanned, pop one '(' from the stack
Now, parentheses are balanced for two conditions:
'(' can be popped from the stack for every ')' found in the string, and
stack is empty at the end (when the entire string is processed)
Actually, there is no need to check any cases "manually". You can just run the following algorithm:
Iterate over the given sequence. Start with an empty stack.
If the current char is an opening bracket, just push it to the stack.
If it's a closing bracket, check that the stack is not empty and the top element of the step is an appropriate opening bracket(that it is, matches this one). If it is not, report an error. Otherwise, pop the top element from the stack.
In the end, the sequence is correct iff the stack is empty.
Why is it correct? Here is a sketch of a proof: if this algorithm reported that the sequence is corrected, it had found a matching pair of all brackets. Thus, the sequence is indeed correct by definition. If it has reported an error:
If the stack was not empty in the end, the balance of opening and closing brackets is not zero. Thus, it is not a correct sequence.
If the stack was empty when we had to pop an element, the balance is off again.
If there was a wrong element on top of the stack, a pair of "wrong" brackets should match each other. It means that the sequence is not correct.
I have shown that:
If the algorithm has reported that the sequence is correct, it is correct.
If the algorithm has reported that the sequence is not correct, it is incorrect(note that I do not use the fact that there are no other cases except those that are mentioned in your question).
This two points imply that this algorithm works for all possible inputs.
public static boolean isBalanced(String s) {
Map<Character, Character> openClosePair = new HashMap<Character, Character>();
openClosePair.put('(', ')');
openClosePair.put('{', '}');
openClosePair.put('[', ']');
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
if (openClosePair.containsKey(s.charAt(i))) {
stack.push(s.charAt(i));
} else if ( openClosePair.containsValue(s.charAt(i))) {
if (stack.isEmpty())
return false;
if (openClosePair.get(stack.pop()) != s.charAt(i))
return false;
}
// ignore all other characters
}
return stack.isEmpty();
}
Ganesan's answer above is not correct and StackOverflow is not letting me comment or Edit his post. So below is the correct answer. Ganesan has an incorrect facing "[" and is missing the stack isEmpty() check.
The below code will return true if the braces are properly matching.
public static boolean isValidExpression(String expression) {
Map<Character, Character> openClosePair = new HashMap<Character, Character>();
openClosePair.put(')', '(');
openClosePair.put('}', '{');
openClosePair.put(']', '[');
Stack<Character> stack = new Stack<Character>();
for(char ch : expression.toCharArray()) {
if(openClosePair.containsKey(ch)) {
if(stack.isEmpty() || stack.pop() != openClosePair.get(ch)) {
return false;
}
} else if(openClosePair.values().contains(ch)) {
stack.push(ch);
}
}
return stack.isEmpty();
}
You're doing some extra checks that aren't needed. Doesn't make any diff to functionality, but a cleaner way to write your code would be:
public static boolean isParenthesisMatch(String str) {
Stack<Character> stack = new Stack<Character>();
char c;
for (int i = 0; i < str.length(); i++) {
c = str.charAt(i);
if (c == '(' || c == '{')
stack.push(c);
else if (stack.empty())
return false;
else if (c == ')') {
if (stack.pop() != '(')
return false;
} else if (c == '}') {
if (stack.pop() != '{')
return false;
}
}
return stack.empty();
}
There is no reason to peek at a paranthesis before removing it from the stack. I'd also consider wrapping instruction blocks in parantheses to improve readability.
public boolean isValid(String s) {
Map<Character, Character> map = new HashMap<>();
map.put('(', ')');
map.put('[', ']');
map.put('{', '}');
Stack<Character> stack = new Stack<>();
for(char c : s.toCharArray()){
if(map.containsKey(c)){
stack.push(c);
} else if(!stack.empty() && map.get(stack.peek())==c){
stack.pop();
} else {
return false;
}
}
return stack.empty();
}
Algorithm is:
1)Create a stack
2)while(end of input is not reached)
i)if the character read is not a sysmbol to be balanced ,ignore it.
ii)if the character is {,[,( then push it to stack
iii)If it is a },),] then if
a)the stack is empty report an error(catch it) i.e not balanced
b)else pop the stack
iv)if element popped is not corresponding to opening sysmbol,then report error.
3) In the end,if stack is not empty report error else expression is balanced.
In Java code:
public class StackDemo {
public static void main(String[] args) throws Exception {
System.out.println("--Bracket checker--");
CharStackArray stack = new CharStackArray(10);
stack.balanceSymbol("[a+b{c+(e-f[p-q])}]") ;
stack.display();
}
}
class CharStackArray {
private char[] array;
private int top;
private int capacity;
public CharStackArray(int cap) {
capacity = cap;
array = new char[capacity];
top = -1;
}
public void push(char data) {
array[++top] = data;
}
public char pop() {
return array[top--];
}
public void display() {
for (int i = 0; i <= top; i++) {
System.out.print(array[i] + "->");
}
}
public char peek() throws Exception {
return array[top];
}
/*Call this method by passing a string expression*/
public void balanceSymbol(String str) {
try {
char[] arr = str.toCharArray();
for (int i = 0; i < arr.length; i++) {
if (arr[i] == '[' || arr[i] == '{' || arr[i] == '(')
push(arr[i]);
else if (arr[i] == '}' && peek() == '{')
pop();
else if (arr[i] == ']' && peek() == '[')
pop();
else if (arr[i] == ')' && peek() == '(')
pop();
}
if (isEmpty()) {
System.out.println("String is balanced");
} else {
System.out.println("String is not balanced");
}
} catch (Exception e) {
System.out.println("String not balanced");
}
}
public boolean isEmpty() {
return (top == -1);
}
}
Output:
--Bracket checker--
String is balanced
Optimized implementation using Stacks and Switch statement:
public class JavaStack {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Stack<Character> s = new Stack<Character>();
while (sc.hasNext()) {
String input = sc.next();
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
switch (c) {
case '(':
s.push(c); break;
case '[':
s.push(c); break;
case '{':
s.push(c); break;
case ')':
if (!s.isEmpty() && s.peek().equals('(')) {
s.pop();
} else {
s.push(c);
} break;
case ']':
if (!s.isEmpty() && s.peek().equals('[')) {
s.pop();
} else {
s.push(c);
} break;
case '}':
if (!s.isEmpty() && s.peek().equals('{')) {
s.pop();
} else {
s.push(c);
} break;
default:
s.push('x'); break;
}
}
if (s.empty()) {
System.out.println("true");
} else {
System.out.println("false");
s.clear();
}
}
} }
Cheers !
import java.util.*;
class StackDemo {
public static void main(String[] argh) {
boolean flag = true;
String str = "(()){}()";
int l = str.length();
flag = true;
Stack<String> st = new Stack<String>();
for (int i = 0; i < l; i++) {
String test = str.substring(i, i + 1);
if (test.equals("(")) {
st.push(test);
} else if (test.equals("{")) {
st.push(test);
} else if (test.equals("[")) {
st.push(test);
} else if (test.equals(")")) {
if (st.empty()) {
flag = false;
break;
}
if (st.peek().equals("(")) {
st.pop();
} else {
flag = false;
break;
}
} else if (test.equals("}")) {
if (st.empty()) {
flag = false;
break;
}
if (st.peek().equals("{")) {
st.pop();
} else {
flag = false;
break;
}
} else if (test.equals("]")) {
if (st.empty()) {
flag = false;
break;
}
if (st.peek().equals("[")) {
st.pop();
} else {
flag = false;
break;
}
}
}
if (flag && st.empty())
System.out.println("true");
else
System.out.println("false");
}
}
I have seen answers here and almost all did well. However, I have written my own version that utilizes a Dictionary for managing the bracket pairs and a stack to monitor the order of detected braces. I have also written a blog post for this.
Here is my class
public class FormulaValidator
{
// Question: Check if a string is balanced. Every opening bracket is matched by a closing bracket in a correct position.
// { [ ( } ] )
// Example: "()" is balanced
// Example: "{ ]" is not balanced.
// Examples: "()[]{}" is balanced.
// "{([])}" is balanced
// "{ ( [ ) ] }" is _not_ balanced
// Input: string, containing the bracket symbols only
// Output: true or false
public bool IsBalanced(string input)
{
var brackets = BuildBracketMap();
var openingBraces = new Stack<char>();
var inputCharacters = input.ToCharArray();
foreach (char character in inputCharacters)
{
if (brackets.ContainsKey(character))
{
openingBraces.Push(character);
}
if (brackets.ContainsValue(character))
{
var closingBracket = character;
var openingBracket = brackets.FirstOrDefault(x => x.Value == closingBracket).Key;
if (openingBraces.Peek() == openingBracket)
openingBraces.Pop();
else
return false;
}
}
return openingBraces.Count == 0;
}
private Dictionary<char, char> BuildBracketMap()
{
return new Dictionary<char, char>()
{
{'[', ']'},
{'(', ')'},
{'{', '}'}
};
}
}
Algorithm to use for checking well balanced parenthesis -
Declare a map matchingParenMap and initialize it with closing and opening bracket of each type as the key-value pair respectively.
Declare a set openingParenSet and initialize it with the values of matchingParenMap.
Declare a stack parenStack which will store the opening brackets '{', '(', and '['.
Now traverse the string expression input.
If the current character is an opening bracket ( '{', '(', '[' ) then push it to the
parenStack.
If the current character is a closing bracket ( '}', ')', ']' ) then pop from
parenStack and if the popped character is equal to the matching starting bracket in
matchingParenMap then continue looping else return false.
After complete traversal if no opening brackets are left in parenStack it means it is a well balanced expression.
I have explained the code snippet of the algorithm used on my blog. Check link - http://hetalrachh.home.blog/2019/12/25/stack-data-structure/
Problem Statement:
Check for balanced parentheses in an expression Or Match for Open Closing Brackets
If you appeared for coding interview round then you might have encountered this problem before. This is a pretty common question and can be solved by using Stack Data Structure
Solution in C#
public void OpenClosingBracketsMatch()
{
string pattern = "{[(((((}}])";
Dictionary<char, char> matchLookup = new Dictionary<char, char>();
matchLookup['{'] = '}';
matchLookup['('] = ')';
matchLookup['['] = ']';
Stack<char> stck = new Stack<char>();
for (int i = 0; i < pattern.Length; i++)
{
char currentChar = pattern[i];
if (matchLookup.ContainsKey(currentChar))
stck.Push(currentChar);
else if (currentChar == '}' || currentChar == ')' || currentChar == ']')
{
char topCharFromStack = stck.Peek();
if (matchLookup[topCharFromStack] != currentChar)
{
Console.WriteLine("NOT Matched");
return;
}
}
}
Console.WriteLine("Matched");
}
For more information, you may also refer to this link: https://www.geeksforgeeks.org/check-for-balanced-parentheses-in-an-expression/
here is my solution using c++
if brackets are matched then returns true if not then gives false
#include <iostream>
#include <stack>
#include <string.h>
using namespace std;
int matchbracket(string expr){
stack<char> st;
int i;
char x;
for(i=0;i<expr.length();i++){
if(expr[i]=='('||expr[i]=='{'||expr[i]=='[')
st.push(expr[i]);
if(st.empty())
return -1;
switch(expr[i]){
case ')' :
x=expr[i];
st.pop();
if(x=='}'||x==']')
return 0;
break;
case '}' :
x=expr[i];
st.pop();
if(x==')'||x==']')
return 0;
break;
case ']' :
x=expr[i];
st.pop();
if(x==')'||x=='}')
return 1;
break;
}
}
return(st.empty());
}
int main()
{
string expr;
cin>>expr;
if(matchbracket(expr)==1)
cout<<"\nTRUE\n";
else
cout<<"\nFALSE\n";
}
This is my implementation for this problem:
public class BalancedBrackets {
static final Set<Character> startBrackets = Set.of('(', '[', '{');
static final Map<Character, Character> bracketsMap = Map.of('(', ')', '[', ']', '{', '}');
public static void main(String[] args) {
// Here you can add test cases
Arrays.asList(
"(())",
"([])",
"()()(())({})"
).forEach(expTest -> System.out.printf("%s is %s balanced%n", expTest, isBalancedBrackets(expTest) ? "" : "not"));
}
public static boolean isBalancedBrackets(String exp) {
Deque<Character> stack = new ArrayDeque<>();
for (int i = 0; i < exp.length(); i++) {
Character chr = exp.charAt(i);
if (bracketsMap.containsKey(chr)) {
stack.push(chr);
continue;
}
if (stack.isEmpty()) {
return false;
}
Character check = stack.pop();
if (bracketsMap.get(check) != chr) {
return false;
}
}
return (stack.isEmpty());
}
}
https://github.com/CMohamed/ProblemSolving/blob/main/other/balanced-brackets/BalancedBrackets.java
//basic code non strack algorithm just started learning java ignore space and time.
/// {[()]}[][]{}
// {[( -a -> }]) -b -> replace a(]}) -> reverse a( }]))->
//Split string to substring {[()]}, next [], next [], next{}
public class testbrackets {
static String stringfirst;
static String stringsecond;
static int open = 0;
public static void main(String[] args) {
splitstring("(()){}()");
}
static void splitstring(String str){
int len = str.length();
for(int i=0;i<=len-1;i++){
stringfirst="";
stringsecond="";
System.out.println("loop starttttttt");
char a = str.charAt(i);
if(a=='{'||a=='['||a=='(')
{
open = open+1;
continue;
}
if(a=='}'||a==']'||a==')'){
if(open==0){
System.out.println(open+"started with closing brace");
return;
}
String stringfirst=str.substring(i-open, i);
System.out.println("stringfirst"+stringfirst);
String stringsecond=str.substring(i, i+open);
System.out.println("stringsecond"+stringsecond);
replace(stringfirst, stringsecond);
}
i=(i+open)-1;
open=0;
System.out.println(i);
}
}
static void replace(String stringfirst, String stringsecond){
stringfirst = stringfirst.replace('{', '}');
stringfirst = stringfirst.replace('(', ')');
stringfirst = stringfirst.replace('[', ']');
StringBuilder stringfirst1 = new StringBuilder(stringfirst);
stringfirst = stringfirst1.reverse().toString();
System.out.println("stringfirst"+stringfirst);
System.out.println("stringsecond"+stringsecond);
if(stringfirst.equals(stringsecond)){
System.out.println("pass");
}
else{
System.out.println("fail");
System.exit(0);
}
}
}
import java.util.Stack;
class Demo
{
char c;
public boolean checkParan(String word)
{
Stack<Character> sta = new Stack<Character>();
for(int i=0;i<word.length();i++)
{
c=word.charAt(i);
if(c=='(')
{
sta.push(c);
System.out.println("( Pushed into the stack");
}
else if(c=='{')
{
sta.push(c);
System.out.println("( Pushed into the stack");
}
else if(c==')')
{
if(sta.empty())
{
System.out.println("Stack is Empty");
return false;
}
else if(sta.peek()=='(')
{
sta.pop();
System.out.println(" ) is poped from the Stack");
}
else if(sta.peek()=='(' && sta.empty())
{
System.out.println("Stack is Empty");
return false;
}
}
else if(c=='}')
{
if(sta.empty())
{
System.out.println("Stack is Empty");
return false;
}
else if(sta.peek()=='{')
{
sta.pop();
System.out.println(" } is poped from the Stack");
}
}
else if(c=='(')
{
if(sta.empty())
{
System.out.println("Stack is empty only ( parenthesis in Stack ");
}
}
}
// System.out.print("The top element is : "+sta.peek());
return sta.empty();
}
}
public class ParaenthesisChehck {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Demo d1= new Demo();
// d1.checkParan(" ");
// d1.checkParan("{}");
//d1.checkParan("()");
//d1.checkParan("{()}");
// d1.checkParan("{123}");
d1.checkParan("{{{}}");
}
}
import java.util.*;
public class Parenthesis
{
public static void main(String...okok)
{
Scanner sc= new Scanner(System.in);
String str=sc.next();
System.out.println(isValid(str));
}
public static int isValid(String a) {
if(a.length()%2!=0)
{
return 0;
}
else if(a.length()==0)
{
return 1;
}
else
{
char c[]=a.toCharArray();
Stack<Character> stk = new Stack<Character>();
for(int i=0;i<c.length;i++)
{
if(c[i]=='(' || c[i]=='[' || c[i]=='{')
{
stk.push(c[i]);
}
else
{
if(stk.isEmpty())
{
return 0;
//break;
}
else
{
char cc=c[i];
if(cc==')' && stk.peek()=='(' )
{
stk.pop();
}
else if(cc==']' && stk.peek()=='[' )
{
stk.pop();
}
else if(cc=='}' && stk.peek()=='{' )
{
stk.pop();
}
}
}
}
if(stk.isEmpty())
{
return 1;
}else
{
return 0;
}
}
}
}
I tried this using javascript below is the result.
function bracesChecker(str) {
if(!str) {
return true;
}
var openingBraces = ['{', '[', '('];
var closingBraces = ['}', ']', ')'];
var stack = [];
var openIndex;
var closeIndex;
//check for opening Braces in the val
for (var i = 0, len = str.length; i < len; i++) {
openIndex = openingBraces.indexOf(str[i]);
closeIndex = closingBraces.indexOf(str[i]);
if(openIndex !== -1) {
stack.push(str[i]);
}
if(closeIndex !== -1) {
if(openingBraces[closeIndex] === stack[stack.length-1]) {
stack.pop();
} else {
return false;
}
}
}
if(stack.length === 0) {
return true;
} else {
return false;
}
}
var testStrings = [
'',
'test',
'{{[][]()()}()}[]()',
'{test{[test]}}',
'{test{[test]}',
'{test{(yo)[test]}}',
'test{[test]}}',
'te()s[]t{[test]}',
'te()s[]t{[test'
];
testStrings.forEach(val => console.log(`${val} => ${bracesChecker(val)}`));
import java.util.*;
public class MatchBrackets {
public static void main(String[] argh) {
String input = "[]{[]()}";
System.out.println (input);
char [] openChars = {'[','{','('};
char [] closeChars = {']','}',')'};
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < input.length(); i++) {
String x = "" +input.charAt(i);
if (String.valueOf(openChars).indexOf(x) != -1)
{
stack.push(input.charAt(i));
}
else
{
Character lastOpener = stack.peek();
int idx1 = String.valueOf(openChars).indexOf(lastOpener.toString());
int idx2 = String.valueOf(closeChars).indexOf(x);
if (idx1 != idx2)
{
System.out.println("false");
return;
}
else
{
stack.pop();
}
}
}
if (stack.size() == 0)
System.out.println("true");
else
System.out.println("false");
}
}
If you want to have a look at my code. Just for reference
public class Default {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numOfString = Integer.parseInt(br.readLine());
String s;
String stringBalanced = "YES";
Stack<Character> exprStack = new Stack<Character>();
while ((s = br.readLine()) != null) {
stringBalanced = "YES";
int length = s.length() - 1;
for (int i = 0; i <= length; i++) {
char tmp = s.charAt(i);
if(tmp=='[' || tmp=='{' || tmp=='('){
exprStack.push(tmp);
}else if(tmp==']' || tmp=='}' || tmp==')'){
if(!exprStack.isEmpty()){
char peekElement = exprStack.peek();
exprStack.pop();
if(tmp==']' && peekElement!='['){
stringBalanced="NO";
}else if(tmp=='}' && peekElement!='{'){
stringBalanced="NO";
}else if(tmp==')' && peekElement!='('){
stringBalanced="NO";
}
}else{
stringBalanced="NO";
break;
}
}
}
if(!exprStack.isEmpty()){
stringBalanced = "NO";
}
exprStack.clear();
System.out.println(stringBalanced);
}
}
}
public static bool IsBalanced(string input)
{
Dictionary<char, char> bracketPairs = new Dictionary<char, char>() {
{ '(', ')' },
{ '{', '}' },
{ '[', ']' },
{ '<', '>' }
};
Stack<char> brackets = new Stack<char>();
try
{
// Iterate through each character in the input string
foreach (char c in input)
{
// check if the character is one of the 'opening' brackets
if (bracketPairs.Keys.Contains(c))
{
// if yes, push to stack
brackets.Push(c);
}
else
// check if the character is one of the 'closing' brackets
if (bracketPairs.Values.Contains(c))
{
// check if the closing bracket matches the 'latest' 'opening' bracket
if (c == bracketPairs[brackets.First()])
{
brackets.Pop();
}
else
// if not, its an unbalanced string
return false;
}
else
// continue looking
continue;
}
}
catch
{
// an exception will be caught in case a closing bracket is found,
// before any opening bracket.
// that implies, the string is not balanced. Return false
return false;
}
// Ensure all brackets are closed
return brackets.Count() == 0 ? true : false;
}
public String checkString(String value) {
Stack<Character> stack = new Stack<>();
char topStackChar = 0;
for (int i = 0; i < value.length(); i++) {
if (!stack.isEmpty()) {
topStackChar = stack.peek();
}
stack.push(value.charAt(i));
if (!stack.isEmpty() && stack.size() > 1) {
if ((topStackChar == '[' && stack.peek() == ']') ||
(topStackChar == '{' && stack.peek() == '}') ||
(topStackChar == '(' && stack.peek() == ')')) {
stack.pop();
stack.pop();
}
}
}
return stack.isEmpty() ? "YES" : "NO";
}
Here's a solution in Python.
#!/usr/bin/env python
def brackets_match(brackets):
stack = []
for char in brackets:
if char == "{" or char == "(" or char == "[":
stack.append(char)
if char == "}":
if stack[-1] == "{":
stack.pop()
else:
return False
elif char == "]":
if stack[-1] == "[":
stack.pop()
else:
return False
elif char == ")":
if stack[-1] == "(":
stack.pop()
else:
return False
if len(stack) == 0:
return True
else:
return False
if __name__ == "__main__":
print(brackets_match("This is testing {([])} if brackets have match."))
Was asked to implement this algorithm at live coding interview, here's my refactored solution in C#:
Git Tests
package com.balance.braces;
import java.util.Arrays;
import java.util.Stack;
public class BalanceBraces {
public static void main(String[] args) {
String[] values = { "()]", "[()]" };
String[] rsult = match(values);
Arrays.stream(rsult).forEach(str -> System.out.println(str));
}
static String[] match(String[] values) {
String[] returnString = new String[values.length];
for (int i = 0; i < values.length; i++) {
String value = values[i];
if (value.length() % 2 != 0) {
returnString[i] = "NO";
continue;
} else {
Stack<Character> buffer = new Stack<Character>();
for (char ch : value.toCharArray()) {
if (buffer.isEmpty()) {
buffer.add(ch);
} else {
if (isMatchedBrace(buffer.peek(), ch)) {
buffer.pop();
} else {
buffer.push(ch);
}
}
if (buffer.isEmpty()) {
returnString[i] = "YES";
} else {
returnString[i] = "FALSE";
}
}
}
}
return returnString;
}
static boolean isMatchedBrace(char start, char endmatch) {
if (start == '{')
return endmatch == '}';
if (start == '(')
return endmatch == ')';
if (start == '[')
return endmatch == ']';
return false;
}
}
in java you don't want to compare the string or char by == signs. you would use equals method. equalsIgnoreCase or something of the like. if you use == it must point to the same memory location. In the method below I attempted to use ints to get around this. using ints here from the string index since every opening brace has a closing brace. I wanted to use location match instead of a comparison match. But i think with this you have to be intentional in where you place the characters of the string. Lets also consider that Yes = true and No = false for simplicity. This answer assumes that you passed an array of strings to inspect and required an array of if yes (they matched) or No (they didn't)
import java.util.Stack;
public static void main(String[] args) {
//String[] arrayOfBraces = new String[]{"{[]}","([{}])","{}{()}","{}","}]{}","{[)]()}"};
// Example: "()" is balanced
// Example: "{ ]" is not balanced.
// Examples: "()[]{}" is balanced.
// "{([])}" is balanced
// "{([)]}" is _not_ balanced
String[] arrayOfBraces = new String[]{"{[]}","([{}])","{}{()}","()[]{}","}]{}","{[)]()}","{[)]()}","{([)]}"};
String[] answers = new String[arrayOfBraces.length];
String openers = "([{";
String closers = ")]}";
String stringToInspect = "";
Stack<String> stack = new Stack<String>();
for (int i = 0; i < arrayOfBraces.length; i++) {
stringToInspect = arrayOfBraces[i];
for (int j = 0; j < stringToInspect.length(); j++) {
if(stack.isEmpty()){
if (openers.indexOf(stringToInspect.charAt(j))>=0) {
stack.push(""+stringToInspect.charAt(j));
}
else{
answers[i]= "NO";
j=stringToInspect.length();
}
}
else if(openers.indexOf(stringToInspect.charAt(j))>=0){
stack.push(""+stringToInspect.charAt(j));
}
else{
String comparator = stack.pop();
int compLoc = openers.indexOf(comparator);
int thisLoc = closers.indexOf(stringToInspect.charAt(j));
if (compLoc != thisLoc) {
answers[i]= "NO";
j=stringToInspect.length();
}
else{
if(stack.empty() && (j== stringToInspect.length()-1)){
answers[i]= "YES";
}
}
}
}
}
System.out.println(answers.length);
for (int j = 0; j < answers.length; j++) {
System.out.println(answers[j]);
}
}
Check balanced parenthesis or brackets with stack--
var excp = "{{()}[{a+b+b}][{(c+d){}}][]}";
var stk = [];
function bracket_balance(){
for(var i=0;i<excp.length;i++){
if(excp[i]=='[' || excp[i]=='(' || excp[i]=='{'){
stk.push(excp[i]);
}else if(excp[i]== ']' && stk.pop() != '['){
return false;
}else if(excp[i]== '}' && stk.pop() != '{'){
return false;
}else if(excp[i]== ')' && stk.pop() != '('){
return false;
}
}
return true;
}
console.log(bracket_balance());
//Parenthesis are balance then return true else false

Infix to Postfix using Stacks Java

I am trying to write a program to convert an infix expression to a postfix expression.
The algorithm that I am using is as follows :
1. Create a stack
2. For each character t in the expression
- If t is an operand, append it to the output
- Else if t is ')',then pop from the stack till '(' is encountered and append
it to the output. do not append '(' to the output.
- If t is an operator or '('
-- If t has higher precedence than the top of the stack, then push t
on to the stack.
-- If t has lower precedence than top of the stack, then keep popping
from the stack and appending to the output until either stack is
empty or a lower priority operator is encountered.
After the input is over, keep popping and appending to the output until the
stack is empty.
Here is my code which prints out wrong results.
public class InfixToPostfix
{
private static boolean isOperator(char c)
{
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^'
|| c == '(' || c == ')';
}
private static boolean isLowerPrecedence(char op1, char op2)
{
switch (op1)
{
case '+':
case '-':
return !(op2 == '+' || op2 == '-');
case '*':
case '/':
return op2 == '^' || op2 == '(';
case '^':
return op2 == '(';
case '(':
return true;
default:
return false;
}
}
public static String convertToPostfix(String infix)
{
Stack<Character> stack = new Stack<Character>();
StringBuffer postfix = new StringBuffer(infix.length());
char c;
for (int i = 0; i < infix.length(); i++)
{
c = infix.charAt(i);
if (!isOperator(c))
{
postfix.append(c);
}
else
{
if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
{
postfix.append(stack.pop());
}
if (!stack.isEmpty())
{
stack.pop();
}
}
else
{
if (!stack.isEmpty() && !isLowerPrecedence(c, stack.peek()))
{
stack.push(c);
}
else
{
while (!stack.isEmpty() && isLowerPrecedence(c, stack.peek()))
{
Character pop = stack.pop();
if (pop != '(')
{
postfix.append(pop);
}
}
}
stack.push(c);
}
}
}
return postfix.toString();
}
public static void main(String[] args)
{
System.out.println(convertToPostfix("A*B-(C+D)+E"));
}
}
The program should print AB*CD+-E+ but it is printing AB*-CD+E.
Why is the output incorrect ?
Also, Is there a more elegant solution to this problem. Please share if you have or know one.
Issue is with your else part:
if (!stack.isEmpty() && !isLowerPrecedence(c, stack.peek()))
{
stack.push(c);
}
else
{
while (!stack.isEmpty() && isLowerPrecedence(c, stack.peek()))
{
Character pop = stack.pop();
if (pop != '(')
{
postfix.append(pop);
}
}
}
stack.push(c);
So here you are pushing the same c element twice with stack.push() when you see stack is not empty and precedence match is higher.
So put this stack.push within else part or remove the push from if condition.
Another issue is, when at the end you have some operators within the stack you dont pop them out.
Here's the code that i came up with for your case:
private static boolean isOperator(char c)
{
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^'
|| c == '(' || c == ')';
}
private static boolean isLowerPrecedence(char op1, char op2)
{
switch (op1)
{
case '+':
case '-':
return !(op2 == '+' || op2 == '-');
case '*':
case '/':
return op2 == '^' || op2 == '(';
case '^':
return op2 == '(';
case '(':
return true;
default:
return false;
}
}
public static String convertToPostfix(String infix)
{
Stack<Character> stack = new Stack<Character>();
StringBuffer postfix = new StringBuffer(infix.length());
char c;
for (int i = 0; i < infix.length(); i++)
{
c = infix.charAt(i);
if (!isOperator(c))
{
postfix.append(c);
}
else
{
if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
{
postfix.append(stack.pop());
}
if (!stack.isEmpty())
{
stack.pop();
}
}
else
{
if (!stack.isEmpty() && !isLowerPrecedence(c, stack.peek()))
{
stack.push(c);
}
else
{
while (!stack.isEmpty() && isLowerPrecedence(c, stack.peek()))
{
Character pop = stack.pop();
if (c != '(')
{
postfix.append(pop);
} else {
c = pop;
}
}
stack.push(c);
}
}
}
}
while (!stack.isEmpty()) {
postfix.append(stack.pop());
}
return postfix.toString();
}
public static void main(String[] args)
{
System.out.println(convertToPostfix("A*B-(C+D)+E"));
}
I think above answer is not correct.
This is the version corrected by me :
package Stack;
import java.util.Stack;
/*
*
Algorithm
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
…..3.1 If the precedence of the scanned operator is greater than the precedence of the operator in the stack(or the stack is empty), push it.
…..3.2 Else, Pop the operator from the stack until the precedence of the scanned operator is less-equal to the precedence of the operator residing on the top of the stack. Push the scanned operator to the stack.
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘ is encountered.
6. Repeat steps 2-6 until infix expression is scanned.
7. Pop and output from the stack until it is not empty.
*/
public class InfixToPostFixEvalution {
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '(' || c == ')';
}
private static int getPrecedence(char ch) {
switch (ch) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
// A utility function to check if the given character is operand
private static boolean isOperand(char ch) {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z');
}
public static String convertToPostfix(String infix) {
Stack<Character> stack = new Stack<Character>();
StringBuffer postfix = new StringBuffer(infix.length());
char c;
for (int i = 0; i < infix.length(); i++) {
c = infix.charAt(i);
if (isOperand(c)) {
postfix.append(c);
} else if (c == '(') {
stack.push(c);
}
// If the scanned character is an ‘)’, pop and output from the stack
// until an ‘(‘ is encountered.
else if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix.append(stack.pop());
}
if (!stack.isEmpty() && stack.peek() != '(')
return null;
else if(!stack.isEmpty())
stack.pop();
}
else if (isOperator(c)) // operator encountered
{
if (!stack.isEmpty() && getPrecedence(c) <= getPrecedence(stack.peek())) {
postfix.append(stack.pop());
}
stack.push(c);
}
}
while (!stack.isEmpty()) {
postfix.append(stack.pop());
}
return postfix.toString();
}
public static void main(String[] args) {
System.out.println(convertToPostfix("a+b*(c^d-e)^(f+g*h)-i"));
}
}
This code inserts the "(" as well in stack and removes accordingly. Just another way of implementing infix to postfix. Here the check is until I do not find lower priority operator in stack I will pop out the value. e.g if stack has - and next operator is +, it will pop - as it is of equal priority.
I have added custom stack implementation, however normal stack provide by java can also be used in place
import chapter4.LinkedListStack(custom stack implementation);
public class InfixToPostfix {
public String infixToPostfix(String str) {
LinkedListStack<String> stack = new LinkedListStack<>();
String[] st = str.split("");
String result = "";
for (String s : st) {
if (operator(s)) {
if (")".equals(s)) {
while (!stack.isEmpty() && !"(".equals(stack.getTop())) {
result += stack.pop();
}
if (!stack.isEmpty()) {
stack.pop();
}
} else {
if (!stack.isEmpty() && !isLowerPrecedence(s, stack.getTop())) {
stack.push(s);
} else {
while (!stack.isEmpty() && isLowerPrecedence(s, stack.getTop())) {
String top = stack.pop();
if (!"(".equals(top)) {
result += top;
}
}
stack.push(s);
}
}
} else {
result += s;
}
}
while (!stack.isEmpty()) {
result += stack.pop();
}
return result;
}
private boolean isLowerPrecedence(String s, String s1) {
switch (s) {
case "+":
return !("+".equals(s1) || "(".equals(s1));
case "-":
return !("-".equals(s1) || "(".equals(s1));
case "*":
return "/".equals(s1) || "^".equals(s1) || "(".equals(s1);
case "/":
return "*".equals(s1) || "^".equals(s1) || "(".equals(s1);
case "^":
return "(".equals(s1);
case "(":
return false;
default:
return false;
}
}
private boolean operator(String s) {
return "+".equals(s) || "-".equals(s) || "*".equals(s) || "/".equals(s) || "^".equals(s) || "(".equals(s) ||
")".equals(s);
}
public static void main(String[] args) {
InfixToPostfix itp = new InfixToPostfix();
System.out.println("The Postfix expression for A*B-(C+D)+E is: " + itp.infixToPostfix("A*B-(C+D)+E"));
System.out.println("The Postfix expression for 1+2*4/5-7+3/6 is: " + itp.infixToPostfix("1+2*4/5-7+3/6"));
System.out.println("The Postfix expression for a+(b*c)/d is: " + itp.infixToPostfix("a+(b*c)/d"));
}
}
public class LinkedListStack<E> {
private Node<E> head;
private static class Node<E> {
E item;
Node<E> next;
public Node(E item, Node<E> next) {
this.item = item;
this.next = next;
}
}
public void push(E item) {
System.out.println("push: " + item);
Node<E> newNode = new Node<>(item, null);
newNode.next = head;
head = newNode;
}
public E pop() {
if (isEmpty()) {
System.out.println("stack is Empty -> empty stack exception");
return null;
}
System.out.println("pop: " + head.item);
E data = head.item;
head = head.next;
return data;
}
public boolean isEmpty() {
return head == null;
}
public E getTop() {
return head.item;
}
}
I think the problem is here:
private static boolean isLowerPrecedence(char op1, char op2)
{
switch (op1)
{
.....
case '(':
return true;
.....
}
In the case '(', false should be returned.
This solution requires proper braces around the original expression, but its quite simple and straight forward compared to other answers I looked at. Just for someone who might need it because the post is an old post.
public static String InfixToPostfix(String origin)
{
String[] params = origin.split(" ");
Stack<String> ops = new Stack<>();
Stack<String> vals = new Stack<>();
for (int i = 0; i < params.length; i++)
{
switch (params[i]) {
case "(":
;
break;
case "+":
ops.push(params[i]);
break;
case "-":
ops.push(params[i]);
break;
case "*":
ops.push(params[i]);
break;
case "/":
ops.push(params[i]);
break;
case "sqrt":
ops.push(params[i]);
break;
// Token not operator or paren: push double value.
case ")":
String d1 = vals.pop();
String d2 = vals.pop();
String op = ops.pop();
vals.push("( " + d2 + " " + d1 + " "+ op + " )");
break;
default:
vals.push(params[i]);
break;
}
}
// System.out.print(vals.pop());
return vals.pop();
}

infix to postfix program not working [duplicate]

This question already has answers here:
Handling parenthesis while converting infix expressions to postfix expressions
(2 answers)
Closed 6 years ago.
I am supposed to write a program to convert infix to postfix. It works for some, but other times not correctly. Especially on infix expressions containing parantheses. Could anyone give me a clue why this is wrong? For example, the infix expression
( ( 5 + 5 * ( 6 - 2 ) + 4 ^ 2 ) * 8 )
returns 5562-*42^++8*((2.
import java.io.*;
import java.util.Scanner;
public class InfixToPostfix
{
//class attributes
private char curValue;
private String postfix;
private LineWriter lw;
private ObjectStack os;
//constructor
public InfixToPostfix(LineWriter l, ObjectStack o)
{
curValue = ' ';
lw=l;
os=o;
}
public String conversion(String buf)
{
String temp =" ";
StringBuffer postfixStrBuf= new StringBuffer(temp);
char popped= new Character(' ');
char topped=' ';
for (int i=0; i<buf.length(); i++)
{
curValue= buf.charAt(i);
if (curValue == '(')
os.push(curValue);
if (curValue == ')')
{
while (popped != '(')
{
popped = ((Character)os.pop());
if (popped != '(')
postfixStrBuf.append(popped);
}
}
if (isOperator(curValue))
{
if( os.isEmpty())
os.push((Character)(curValue));
else
topped=((Character)os.top());
if ( (priority(topped)) >= (priority(curValue)) && (topped != ' ') )
{
popped = ((Character)os.pop());
if (popped != '(')
postfixStrBuf.append(popped);
//if it is a left paranthess, we want to go ahead and push it anyways
os.push((Character)(curValue));
}
if ( (priority(topped)) < (priority(curValue)) && (topped != ' ') )
os.push((Character)(curValue));
}
else if (!isOperator(curValue) && (curValue != ' ') && (curValue != '(' ) && (curValue != ')' ))
postfixStrBuf.append(curValue);
}
//before you grab the next line of the file , pop off whatever is remaining off the stack and append it to
//the infix expression
getRemainingOp(postfixStrBuf);
return postfix;
//postfixStrBuf.delete(0, postfixStrBuf.length());
}
public int priority(char curValue)
{
switch (curValue)
{
case '^': return 3;
case '*':
case '/': return 2;
case '+':
case '-': return 1;
default : return 0;
}
}
public boolean isOperator(char curValue)
{
boolean operator = false;
if ( (curValue == '^' ) || (curValue == '*') || (curValue == '/') || (curValue == '+' ) || (curValue == '-') )
operator = true;
return operator;
}
public String getRemainingOp(StringBuffer postfixStrBuf)
{
char popped=' ';
while ( !(os.isEmpty()) )
{
opped = ((Character)os.pop());
postfixStrBuf.append(popped);
}
postfix=postfixStrBuf.toString();
return postfix;
}
}
I will only post how the inner loop should look like (without the castings everywhere):
if (curValue == '(') {
os.push(curValue);
} else if (curValue == ')') {
if(!os.isEmpty()) {
topped = os.pop();
while (!os.isEmpty() && (topped != '(')) {
postfixStrBuf.append(topped);
topped = os.pop();
}
}
} else if (isOperator(curValue)) {
if (os.isEmpty()) {
os.push(curValue);
} else {
while(!os.isEmpty() && (priority(os.top()) >= priority(curValue))) {
popped = os.pop();
postfixStrBuf.append(popped);
}
os.push(curValue);
}
} else if (curValue != ' ') {
postfixStrBuf.append(curValue);
}
Disclosure: it is pretty late already so I hope it is fine. You should fix the way variables are initialized and return of the getRemainingOp method.

Categories

Resources