Convert Infix to Postfix with Stack [duplicate] - java

This question already has answers here:
Handling parenthesis while converting infix expressions to postfix expressions
(2 answers)
Closed 5 years ago.
I have to make a program that changes an expression written in Infix notation to Postfix notation. I am running into a problem when I start using parentheses. For example, when I put in "a + (c - h) / (b * d)" is comes out as "ac+h-b/d*" when it should come out as "a c h - b d * / +." Would really appreciate the help. Thanks.
import java.util.Scanner;
import java.util.Stack;
public class PostfixConverter {
static private String expression;
private Stack<Character> stack = new Stack<Character>();
public PostfixConverter(String infixExpression) {
expression = infixExpression;
}
public String infixToPostfix() {
String postfixString = "";
for (int index = 0; index < expression.length(); ++index) {
char value = expression.charAt(index);
if (value == '(') {
} else if (value == ')') {
Character oper = stack.peek();
while (!(oper.equals('(')) && !(stack.isEmpty())) {
stack.pop();
postfixString += oper.charValue();
}
} else if (value == '+' || value == '-') {
if (stack.isEmpty()) {
stack.push(value);
} else {
Character oper = stack.peek();
while (!(stack.isEmpty() || oper.equals(('(')) || oper.equals((')')))) {
stack.pop();
postfixString += oper.charValue();
}
stack.push(value);
}
} else if (value == '*' || value == '/') {
if (stack.isEmpty()) {
stack.push(value);
} else {
Character oper = stack.peek();
while (!oper.equals(('+')) && !oper.equals(('-')) && !stack.isEmpty()) {
stack.pop();
postfixString += oper.charValue();
}
stack.push(value);
}
} else {
postfixString += value;
}
}
while (!stack.isEmpty()) {
Character oper = stack.peek();
if (!oper.equals(('('))) {
stack.pop();
postfixString += oper.charValue();
}
}
return postfixString;
}
public static void main(String[] args) {
System.out.println("Type an expression written in Infix notation: ");
Scanner input = new Scanner(System.in);
String expression = input.next();
PostfixConverter convert = new PostfixConverter(expression);
System.out.println("This expression writtien in Postfix notation is: \n" + convert.infixToPostfix());
}
}

You provided code is similar to this. But that code also does not work.
I have updated your code and added the comments of the changes.
import java.util.Scanner;
import java.util.Stack;
public class PostfixConverter {
static private String expression;
private Stack<Character> stack = new Stack<Character>();
public PostfixConverter(String infixExpression) {
expression = infixExpression;
}
public String infixToPostfix() {
String postfixString = "";
for (int index = 0; index < expression.length(); ++index) {
char value = expression.charAt(index);
if (value == '(') {
stack.push('('); // Code Added
} else if (value == ')') {
Character oper = stack.peek();
while (!(oper.equals('(')) && !(stack.isEmpty())) {
stack.pop();
postfixString += oper.charValue();
if (!stack.isEmpty()) // Code Added
oper = stack.peek(); // Code Added
}
stack.pop(); // Code Added
} else if (value == '+' || value == '-') {
if (stack.isEmpty()) {
stack.push(value);
} else {
Character oper = stack.peek();
while (!(stack.isEmpty() || oper.equals(('(')) || oper.equals((')')))) {
oper = stack.pop(); // Code Updated
postfixString += oper.charValue();
}
stack.push(value);
}
} else if (value == '*' || value == '/') {
if (stack.isEmpty()) {
stack.push(value);
} else {
Character oper = stack.peek();
// while condition updated
while (!oper.equals(('(')) && !oper.equals(('+')) && !oper.equals(('-')) && !stack.isEmpty()) {
oper = stack.pop(); // Code Updated
postfixString += oper.charValue();
}
stack.push(value);
}
} else {
postfixString += value;
}
}
while (!stack.isEmpty()) {
Character oper = stack.peek();
if (!oper.equals(('('))) {
stack.pop();
postfixString += oper.charValue();
}
}
return postfixString;
}
public static void main(String[] args) {
System.out.println("Type an expression written in Infix notation: ");
Scanner input = new Scanner(System.in);
String expression = input.next();
PostfixConverter convert = new PostfixConverter(expression);
System.out.println("This expression writtien in Postfix notation is: \n" + convert.infixToPostfix());
}
}

You need to use associativity and compare operator precedence. I have mostly covered all the operators.
Pre-requiste - Expression should be splitted by space ' '.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;
public class Test{
public static final int LEFT_ASSOC = 0;
public static final int RIGHT_ASSOC = 1;
public static final Map<String, int[]> ARITH_OPERATORS = new HashMap<String, int[]>();
public static final Map<String, int[]> REL_OPERATORS = new HashMap<String, int[]>();
public static final Map<String, int[]> LOG_OPERATORS = new HashMap<String, int[]>();
public static final Map<String, int[]> OPERATORS = new HashMap<String, int[]>();
static {
ARITH_OPERATORS.put("+", new int[] { 25, LEFT_ASSOC });
ARITH_OPERATORS.put("-", new int[] { 25, LEFT_ASSOC });
ARITH_OPERATORS.put("*", new int[] { 30, LEFT_ASSOC });
ARITH_OPERATORS.put("/", new int[] { 30, LEFT_ASSOC });
ARITH_OPERATORS.put("%", new int[] { 30, LEFT_ASSOC });
ARITH_OPERATORS.put("^", new int[] { 35, RIGHT_ASSOC });
ARITH_OPERATORS.put("**", new int[] { 30, LEFT_ASSOC });
REL_OPERATORS.put("<", new int[] { 20, LEFT_ASSOC });
REL_OPERATORS.put("<=", new int[] { 20, LEFT_ASSOC });
REL_OPERATORS.put(">", new int[] { 20, LEFT_ASSOC });
REL_OPERATORS.put(">=", new int[] { 20, LEFT_ASSOC });
REL_OPERATORS.put("==", new int[] { 20, LEFT_ASSOC });
REL_OPERATORS.put("!=", new int[] { 20, RIGHT_ASSOC });
LOG_OPERATORS.put("!", new int[] { 15, RIGHT_ASSOC });
LOG_OPERATORS.put("&&", new int[] { 10, LEFT_ASSOC });
LOG_OPERATORS.put("||", new int[] { 5, LEFT_ASSOC });
LOG_OPERATORS.put("EQV", new int[] { 0, LEFT_ASSOC });
LOG_OPERATORS.put("NEQV", new int[] { 0, LEFT_ASSOC });
OPERATORS.putAll(ARITH_OPERATORS);
OPERATORS.putAll(REL_OPERATORS);
OPERATORS.putAll(LOG_OPERATORS);
}
public static void main(String args[]) {
String inputExpression = "a + ( c - h ) / ( b * d )";
String[] input = inputExpression.split(" ");
List<String> output = infixToRPN(input);
System.out.println(output.toString());
}
private static boolean isAssociative(String token, int type) {
if (!isOperator(token)) {
System.out.println("");
}
if (OPERATORS.get(token)[1] == type) {
return true;
}
return false;
}
private static boolean isOperator(String token) {
return OPERATORS.containsKey(token);
}
private static int cmpPrecedence(String token1, String token2) {
if (!isOperator(token1) || !isOperator(token2)) {
System.out.println("");
}
return OPERATORS.get(token1)[0] - OPERATORS.get(token2)[0];
}
private static ArrayList<String> infixToRPN(String[] inputTokens) {
ArrayList<String> out = new ArrayList<String>();
Stack<String> stack = new Stack<String>();
// For all the input tokens [S1] read the next token [S2]
for (String token : inputTokens) {
if (isOperator(token)) {
// If token is an operator (x) [S3]
while (!stack.empty() && isOperator(stack.peek())) {
// [S4]
if ((isAssociative(token, LEFT_ASSOC) && cmpPrecedence(token, stack.peek()) <= 0)
|| (isAssociative(token, RIGHT_ASSOC) && cmpPrecedence(token, stack.peek()) < 0)) {
out.add(stack.pop()); // [S5] [S6]
continue;
}
break;
}
// Push the new operator on the stack [S7]
stack.push(token);
} else if (token.equals("(")) {
stack.push(token); // [S8]
} else if (token.equals(")")) {
// [S9]
while (!stack.empty() && !stack.peek().equals("(")) {
out.add(stack.pop()); // [S10]
}
stack.pop(); // [S11]
} else {
out.add(token); // [S12]
}
}
while (!stack.empty()) {
out.add(stack.pop()); // [S13]
}
return out;
}
}
output
[a, c, h, -, b, d, *, /, +]

Related

How do i properly add characters to string in recursion

So i have this function EDIT:Whole program as requested
//This is a java program to construct Expression Tree using Infix Expression
import java.io.*;
public class Infix_Expression_Tree
{
public static void main(String args[]) throws IOException
{
String result="";
File vhod = new File(args[0]);
try{
BufferedReader reader = new BufferedReader(new FileReader(vhod));
Tree t1 = new Tree();
String a = reader.readLine();
t1.insert(a);
t1.traverse(1,result);
System.out.println("rez "+ result);
ch = reader.readLine();
}catch(IOException e){
e.printStackTrace();
}
}
}
class Node
{
public char data;
public Node leftChild;
public Node rightChild;
public Node(char x)
{
data = x;
}
public void displayNode()
{
System.out.print(data);
}
}
class Stack1
{
private Node[] a;
private int top, m;
public Stack1(int max)
{
m = max;
a = new Node[m];
top = -1;
}
public void push(Node key)
{
a[++top] = key;
}
public Node pop()
{
return (a[top--]);
}
public boolean isEmpty()
{
return (top == -1);
}
}
class Stack2
{
private char[] a;
private int top, m;
public Stack2(int max)
{
m = max;
a = new char[m];
top = -1;
}
public void push(char key)
{
a[++top] = key;
}
public char pop()
{
return (a[top--]);
}
public boolean isEmpty()
{
return (top == -1);
}
}
class Conversion
{
private Stack2 s;
private String input;
private String output = "";
public Conversion(String str)
{
input = str;
s = new Stack2(str.length());
}
public String inToPost()
{
for (int i = 0; i < input.length(); i++)
{
char ch = input.charAt(i);
switch (ch)
{
case '+':
gotOperator(ch, 2);
break;
case '*':
gotOperator(ch,1);
break;
case '/':
gotOperator(ch, 3);
break;
case '(':
s.push(ch);
break;
case ')':
gotParenthesis();
//s.pop();
break;
default:
//gotOperator(ch, 0);
//break;
output = output + ch;
}
}
while (!s.isEmpty())
output = output + s.pop();
//System.out.println("to je output iz inToPost " +output);
return output;
}
private void gotOperator(char opThis, int prec1)
{
while (!s.isEmpty())
{
char opTop = s.pop();
if (opTop == '(')
{
s.push(opTop);
break;
} else
{
int prec2;
if (opTop == '+')
prec2 = 2;
else if(opTop=='*')
prec2=1;
else
prec2 = 3;
if (prec2 <= prec1)
{
s.push(opTop);
break;
} else
output = output + opTop;
}
}
s.push(opThis);
}
private void gotParenthesis()
{
while (!s.isEmpty())
{
char ch = s.pop();
if (ch == '(')
break;
else
output = output + ch;
}
}
}
class Tree
{
private Node root;
public Tree()
{
root = null;
}
public void insert(String s)
{
Conversion c = new Conversion(s);
s = c.inToPost();
Stack1 stk = new Stack1(s.length());
s = s + "#";
int i = 0;
char symbol = s.charAt(i);
Node newNode;
while (symbol != '#')
{
if (symbol >= '0' && symbol <= '9' || symbol >= 'A'
&& symbol <= 'Z' || symbol >= 'a' && symbol <= 'z')
{
newNode = new Node(symbol);
stk.push(newNode);
} else if (symbol == '+' || symbol == '/'
|| symbol == '*')
{
Node ptr1=null;
Node ptr2=null;
//if(!stk.isEmpty()){
ptr1 = stk.pop();
if(!stk.isEmpty()){
ptr2 = stk.pop();
}
//}
newNode = new Node(symbol);
newNode.leftChild = ptr2;
newNode.rightChild = ptr1;
stk.push(newNode);
}
/*else if(symbol=='/'){
Node ptr = stk.pop();
newNode = new Node(symbol);
newNode.leftChild = ptr;
newNode.rightChild=null;
stk.push(newNode);
}*/
symbol = s.charAt(++i);
}
root = stk.pop();
}
public void traverse(int type,String result)
{
System.out.println("Preorder Traversal:- ");
preOrder(root,result);
}
private void preOrder(Node localRoot, String result)
{
if(root==null){
return;
}
if (localRoot != null)
{
if(localRoot.data == '/'){
preOrder(localRoot.leftChild,result);
result=result + localRoot.data;
//StringBuilder stringBuilder1 = new StringBuilder();
//stringBuilder1.append(result).append(localRoot.data);
System.out.println(result);
//localRoot.displayNode();
preOrder(localRoot.rightChild,result);
return;
}else{
//System.out.println("trenutni root je" );
//localRoot.displayNode();
result=result + localRoot.data;
// StringBuilder stringBuilder1 = new StringBuilder();
//stringBuilder1.append(result).append(localRoot.data);
System.out.println(result);
preOrder(localRoot.leftChild,result);
//result=result + localRoot.data;
//System.out.print(root.data);
preOrder(localRoot.rightChild,result);
//System.out.print(root.data);
//preOrder(localRoot.rightChild);
return;
}
}
}
}
my problem with it is that with localRoot.DisplayNode() i get the result i want. But when i add the same thing to the String result it adds data, until i get to leaf of the tree(leaf doesnt have left/right child) so it returns to previous recursive call, and goes to right child, here somewhere the leaf(from which we came back) isnt in String anymore. How do i fix this?
String is defined in main method

Parenthesis creation in the infix expression using stack in java

I need to write a Java program that takes from the standard input a valid Right Parenthesized Infix Expression (RPIE) and outputs the equivalent Full Parenthesized Infix Expression (FPIE). For example, if the input is: a+20)/b-c)53.4-d))) , the output should be ((a+20)/((b-c)(53.4-d))).
I have tried to implement as follows but did not reach the solution. Could anyone help me?
import java.util.Scanner;
import java.util.Stack;
public class ParenthesisCreator {
static private String expression;
private Stack<Character> stack = new Stack<Character>();
public ParenthesisCreator(String input) {
expression = input;
}
public String rtParenthesisInfixToFullParenthesis() {
String postfixString = "";
for (int index = 0; index < expression.length(); ++index) {
char value = expression.charAt(index);
if (value == ')') {
stack.push(')');
stack.push('(');
Character oper = stack.peek();
while (!stack.isEmpty()) {
stack.pop();
postfixString += oper.charValue();
if (!stack.isEmpty())
oper = stack.peek();
}
} else {
postfixString += value;
}
}
return postfixString;
}
public static void main(String[] args) {
System.out.println("Type an expression written in right parenthesized infix: ");
Scanner input = new Scanner(System.in);
String expression = input.next();
// Input: a+20)/b-c)*53.4-d)))
// Desired output is: ((a+20)/((b-c)*(53.4-d)))
ParenthesisCreator convert = new ParenthesisCreator(expression);
System.out.println("This expression writtien in full parenthesized is: \n" + convert.rtParenthesisInfixToFullParenthesis());
}
}
public final class ParenthesisCreator implements Function<String, String> {
private final IntPredicate isOperator;
public ParenthesisCreator() {
this(ch -> ch == '/' || ch == '*' || ch == '+' || ch == '-');
}
public ParenthesisCreator(IntPredicate isOperator) {
this.isOperator = isOperator;
}
#Override
public String apply(String expr) {
Deque<String> stack = new LinkedList<>();
StringBuilder buf = null;
for (int i = 0; i < expr.length(); i++) {
char ch = expr.charAt(i);
if (ch == ')') {
if (buf != null) {
stack.push(buf.insert(0, '(').append(')').toString());
buf = null;
} else if (stack.size() >= 2) {
String two = stack.pop();
String one = stack.pop();
stack.push('(' + one + two + ')');
} else
throw new IllegalArgumentException();
} else if (isOperator.test(ch) && buf == null && !stack.isEmpty())
stack.push(stack.pop() + ch);
else
(buf = buf == null ? new StringBuilder() : buf).append(ch);
}
return String.join("", stack);
}
}
Demo
System.out.println(new ParenthesisCreator().apply("a+20)/b-c)53.4-d)))")); // ((a+20)/((b-c)(53.4-d)))
public class FixExpressionParentheses {
public String fixExpression(String expression) {
String[] tokenArray = expression.split(" ");
Stack<String> operators = new Stack<>();
Stack<String> operands = new Stack<>();
for (String token: tokenArray) {
switch (token) {
case "+", "-", "*", "/", "sqrt" -> operators.push(token);
case ")" -> {
String operator = operators.pop();
String operandTwo = operands.pop();
String operandOne = operands.pop();
String newToken = "( " + operandOne + " " + operator + " "
+ operandTwo + " )";
operands.push(newToken);
}
default -> operands.push(token);
}
}
return operands.pop();
}
}

Infix to postfix digit or letter concatenation

working on a program that converts infix notation to postfix. I have it working for most instances except when character concatenation is required. For example, if I pass in a string of numbers (1002+304) it outputs 1, 0, 0, 2, 3, 0, 4, + instead of 1002, 304, +.
import java.util.*;
public class InfixToPostfix {
private Deque<String> postfix; // Used as a queue of String
private static boolean isOperator(char op)
{
if(op=='+'||op=='-'||op=='*'||op=='/'||op=='^'
||op=='('||op==')')
{
return true;
}
return false;
}
private static boolean lowerEqualPrec(char op1, char op2)
{
boolean flag = false;
if(op1=='+'|| op1=='-')
{
if(op2=='+'||op2=='-'||op2=='*'||op2=='/'||op2=='^')
{
flag= true;
}
}else if(op1=='*' || op1=='/')
{
if(op2=='*'||op2=='/'||op2=='^')
{
flag= true;
}
}else if(op1=='^')
{
flag= false;
}else if(op1=='(')
{
flag= false;
}
return flag;
}
public InfixToPostfix(String infix)
{
for(int i=0; i<infix.length(); i++)
{
if(infix.length() ==0 || infix.charAt(0)==')' ||
infix.charAt(i)=='&' || infix.charAt(infix.length()-1)=='(')
{
throw new IllegalArgumentException();
}
}
postfix = new LinkedList<String>();
Stack<Character> stack = new Stack<Character>();
Character ch;
String digits="";
String letters = "";
for(int i=0; i<infix.length(); i++)
{
ch=infix.charAt(i);
if(ch == ' ')
{
//do nothing
}
if(Character.isDigit(ch))
{
digits=""+ch;
if(i+1 >= infix.length() || !Character.isDigit(infix.charAt(i+1)))
{
digits=digits+"";
}
postfix.add(digits);
}
if(Character.isLetter(ch))
{
letters=ch+"";
postfix.add(letters);
}
if(isOperator(ch))
{
if(ch == ')')
{
if(!stack.isEmpty() && stack.peek() != '(')
{
postfix.add(""+stack.pop());
if(!stack.isEmpty())
{
stack.pop();
}
}
}
else
{
if(!stack.isEmpty() && !lowerEqualPrec(ch, stack.peek()))
{
stack.push(ch);
}
else
{
while(!stack.isEmpty() && lowerEqualPrec(ch, stack.peek()))
{
char pop = stack.pop();
if(ch!='(')
{
postfix.add(pop+"");
}
}
stack.push(ch);
}
}
}
}
while(!stack.isEmpty()&&stack.peek()!='(')
{
postfix.add(stack.pop()+"");
}
System.out.println(postfix);
}
public Iterator<String> iterator()
{
return new PostfixIterator(postfix) ;
}
public static void main(String[] args)
{
InfixToPostfix test = new InfixToPostfix("1002+304");
}
}
For postfixConversion
public static String postfixConversion(String input) {
int i;
String postfix = "";
Stack<Character> stack = new Stack<Character>();
for (i = 0; i < input.length(); i++) {
while (input.charAt(i) == ' ') {
++i;
}
if (Character.isDigit(input.charAt(i))) {
postfix += input.charAt(i);
//if (!Character.isDigit(input.charAt(i+1))) {
postfix += ' ';
//}
}
else if (precedenceLevel(input.charAt(i)) != 0) {
while ((!stack.isEmpty()) && (precedenceLevel(stack.peek()) >= precedenceLevel(input.charAt(i))) && (stack.peek() != '(')) {
postfix += stack.peek();
postfix += ' ';
stack.pop();
}
stack.push(input.charAt(i));
}
else if (input.charAt(i) == '(') {
stack.push(input.charAt(i));
}
else if (input.charAt(i) == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix += stack.peek();
stack.pop();
}
stack.pop();
}
}
while (!stack.isEmpty()) {
postfix += stack.peek();
postfix += ' ';
}
return postfix;
}

How to do precedence with multiple exponentials, ^, in an arithmetic equation

I am working on a program that solves arithmetic equations. I have encountered a problem that occurs when there are multiple exponential statements in a row the program does not correctly solve them. An example would be: 2^3^2, the correct answer is 512 but the program outputs 64. This is because the program does 2^3 and then 8^2, instead of doing 3^2 and then 2^9. Let me know if you have any ideas on how to modify my current code or have something to add.
import java.text.DecimalFormat;
import java.util.EmptyStackException;
import myUtil.*;
public class PostFixEvaluator extends Asg6
{
public static class SyntaxErrorException extends Exception
{
SyntaxErrorException(String message)
{
super(message);
}
}
private static final String operators = "+-*/^()";
private AStack<Double> operandStack;
private double evaluateOP(char op) throws Exception
{
double rightside = operandStack.pop();
double leftside = operandStack.pop();
double result = 0;
if(op == '+')
{
result = leftside + rightside;
}
else if(op == '-')
{
result = leftside - rightside;
}
else if(op == '*')
{
result = leftside * rightside;
}
else if(op == '/')
{
if(rightside == 0)
{
throw new Exception("Can not divide by 0, the equation is undefined");
}
else
{
result = leftside / rightside;
}
}
else if(op == '^')
{
result = Math.pow(leftside, rightside);
}
return result;
}
private boolean isOperator(char ch)
{
return operators.indexOf(ch) != -1;
}
public double evaluate(String exp) throws Exception
{
operandStack = new AStack<Double>();
String[] tokens = exp.split("\\s+");
try
{
for(String nextToken : tokens)
{
char firstChar = nextToken.charAt(0);
if(Character.isDigit(firstChar))
{
double value = Double.parseDouble(nextToken);
operandStack.push(value);
}
else if (isOperator(firstChar))
{
double result = evaluateOP(firstChar);
operandStack.push(result);
}
else
{
throw new Exception("Invalid character: " + firstChar);
}
}
double answer = operandStack.pop();
if(operandStack.empty())
{
return answer;
}
else
{
throw new Exception("Syntax Error: Stack should be empty");
}
}
catch(EmptyStackException ex)
{
throw new Exception("Syntax Error: The stack is empty");
}
}
}
You're trying to use an LL(1) grammar (which is what a recursive descent parser can parse) to model a right-associative operator (^). A right-associative operator requires left recursion, which doesn't work so easily with LL(1) grammars. You'll want to look at left factoring: http://en.wikipedia.org/wiki/LL_parser#Left_Factoring
I would solve this with operator Priorities as you might want to have them anyway.
For testing i changed the class a bit, so i could test it and its sure not most efficient or readable but you should get
the idea how it works.
import java.text.DecimalFormat;
import java.util.EmptyStackException;
import java.util.*;
public class PostFixEvaluator
{
public static class SyntaxErrorException extends Exception
{
SyntaxErrorException(String message)
{
super(message);
}
}
private static final String operators = "+-*/^()";
private static int[] operatorPriority = {1,1,2,2,3,10,10};
private Stack<Double> operandStack;
private Stack<Character> operatorStack;
private double evaluateOP(char op) throws Exception
{
double rightside = operandStack.pop();
double leftside = operandStack.pop();
double result = 0;
if(op == '+')
{
result = leftside + rightside;
}
else if(op == '-')
{
result = leftside - rightside;
}
else if(op == '*')
{
result = leftside * rightside;
}
else if(op == '/')
{
if(rightside == 0)
{
throw new Exception("Can not divide by 0, the equation is undefined");
}
else
{
result = leftside / rightside;
}
}
else if(op == '^')
{
result = Math.pow(leftside, rightside);
}
return result;
}
private boolean isOperator(char ch)
{
return operators.indexOf(ch) != -1;
}
public double evaluate(String exp) throws Exception
{
operandStack = new Stack<Double>();
operatorStack = new Stack<Character>();
String[] tokens = exp.split("\\s+");
try
{
for(String nextToken : tokens)
{
char firstChar = nextToken.charAt(0);
if(Character.isDigit(firstChar))
{
double value = Double.parseDouble(nextToken);
operandStack.push(value);
}
else if (isOperator(firstChar))
{
// Try to evaluate the operators on the stack
while (!operatorStack.isEmpty())
{
char tmpOperator = operatorStack.pop();
// If Operator has higher Priority than the one before,
// Calculate it first if equal first calculate the second
// operator to get the ^ problem fixed
if (operatorPriority[operators.indexOf(firstChar)] >= operatorPriority[operators.indexOf(tmpOperator)])
{
operatorStack.push(tmpOperator);
// Operand has to be fetched first
break;
}
else
{
double result = evaluateOP(tmpOperator);
operandStack.push(result);
}
}
operatorStack.push(firstChar);
}
else
{
throw new Exception("Invalid character: " + firstChar);
}
}
// Here we need to calculate the operators left on the stack
while (!operatorStack.isEmpty())
{
char tmpOperator = operatorStack.pop();
// Operator Priority has to be descending,
// or the code before is wrong.
double result = evaluateOP(tmpOperator);
operandStack.push(result);
}
double answer = operandStack.pop();
if(operandStack.empty())
{
return answer;
}
else
{
throw new Exception("Syntax Error: Stack should be empty");
}
}
catch(EmptyStackException ex)
{
throw new Exception("Syntax Error: The stack is empty");
}
}
// For testing Only
public static void main(String[] args) throws Exception
{
PostFixEvaluator e = new PostFixEvaluator();
System.out.println(e.evaluate("2 ^ 3 ^ 2"));
}
}

Java Expression Parser & Calculator Shunting Yard Algorithm

So the task is to create our own parser for a expression calculator. For Example:
Input: 3+2*1-6/3
Output: 3
Input: 3++2
Output: Invalid Expression
Input: -5+2
Output: -3
Input: 5--2
Output: 7
The code here solves a part of the problem except that it has a fixed input and negative values cannot be solved, And I'm not quite sure yet if it really does solve the expression with operator precedence.
but I already modified it to get an input expression from the user.
and I've been wondering for hours how to implement the solving for negative values. help anyone?
NO JAVASCRIPT ENGINE PLEASE.
here's the current code
import java.util.*;
public class ExpressionParser
{
// Associativity constants for operators
private static final int LEFT_ASSOC = 0;
private static final int RIGHT_ASSOC = 1;
// Operators
private static final Map<String, int[]> OPERATORS = new HashMap<String, int[]>();
static
{
// Map<"token", []{precendence, associativity}>
OPERATORS.put("+", new int[] { 0, LEFT_ASSOC });
OPERATORS.put("-", new int[] { 0, LEFT_ASSOC });
OPERATORS.put("*", new int[] { 5, LEFT_ASSOC });
OPERATORS.put("/", new int[] { 5, LEFT_ASSOC });
}
// Test if token is an operator
private static boolean isOperator(String token)
{
return OPERATORS.containsKey(token);
}
// Test associativity of operator token
private static boolean isAssociative(String token, int type)
{
if (!isOperator(token))
{
throw new IllegalArgumentException("Invalid token: " + token);
}
if (OPERATORS.get(token)[1] == type) {
return true;
}
return false;
}
// Compare precedence of operators.
private static final int cmpPrecedence(String token1, String token2)
{
if (!isOperator(token1) || !isOperator(token2))
{
throw new IllegalArgumentException("Invalid tokens: " + token1
+ " " + token2);
}
return OPERATORS.get(token1)[0] - OPERATORS.get(token2)[0];
}
// Convert infix expression format into reverse Polish notation
public static String[] expToRPN(String[] inputTokens)
{
ArrayList<String> out = new ArrayList<String>();
Stack<String> stack = new Stack<String>();
// For each token
for (String token : inputTokens)
{
// If token is an operator
if (isOperator(token))
{
// While stack not empty AND stack top element
// is an operator
while (!stack.empty() && isOperator(stack.peek()))
{
if ((isAssociative(token, LEFT_ASSOC) &&
cmpPrecedence(token, stack.peek()) <= 0) ||
(isAssociative(token, RIGHT_ASSOC) &&
cmpPrecedence(token, stack.peek()) < 0))
{
out.add(stack.pop());
continue;
}
break;
}
// Push the new operator on the stack
stack.push(token);
}
// If token is a left bracket '('
else if (token.equals("("))
{
stack.push(token); //
}
// If token is a right bracket ')'
else if (token.equals(")"))
{
while (!stack.empty() && !stack.peek().equals("("))
{
out.add(stack.pop());
}
stack.pop();
}
// If token is a number
else
{
// if(!isOperator(stack.peek())){
// out.add(String.valueOf(token*10));
// }
out.add(token);
}
}
while (!stack.empty())
{
out.add(stack.pop());
}
String[] output = new String[out.size()];
return out.toArray(output);
}
public static double RPNtoDouble(String[] tokens)
{
Stack<String> stack = new Stack<String>();
// For each token
for (String token : tokens) //for each
{
// If the token is a value push it onto the stack
if (!isOperator(token))
{
stack.push(token);
}
else
{
// Token is an operator: pop top two entries
Double d2 = Double.valueOf( stack.pop() );
Double d1 = Double.valueOf( stack.pop() );
//Get the result
Double result = token.compareTo("*") == 0 ? d1 * d2 :
token.compareTo("/") == 0 ? d1 / d2 :
token.compareTo("+") == 0 ? d1 + d2 :
d1 - d2;
// Push result onto stack
stack.push( String.valueOf( result ));
}
}
return Double.valueOf(stack.pop());
}
public static void main(String[] args) throws Exception{
Scanner in = new Scanner(System.in);
String reg = "((?<=[<=|>=|==|\\+|\\*|\\-|<|>|/|=])|(?=[<=|>=|==|\\+|\\*|\\-|<|>|/|=]))";
while(true){
try{
System.out.println("Enter Your Expression");
//String[] input = "( 1 + 2 ) * ( 3 / 4 ) - ( 5 + 6 )".split(" ");
String[] input = in.nextLine() .split(reg);
String[] output = expToRPN(input);
// Build output RPN string minus the commas
System.out.print("Stack: ");
for (String token : output) {
System.out.print("[ ");System.out.print(token + " "); System.out.print("]");
}
System.out.println(" ");
// Feed the RPN string to RPNtoDouble to give result
Double result = RPNtoDouble( output );
System.out.println("Answer= " + result);
}catch (NumberFormatException | EmptyStackException nfe){
System.out.println("INVALID EXPRESSION"); }
}
}
}
UPDATED CODE:
Added: unaryToexp() function.
what I wanted to do was that everytime a " - " occurs, the code treats it as a binary by changing it to " _ " as another operator and this operator solves multiplies thing by -1 (what I wanted first was to add [-1] and [*] to the rpn stack). still got problems here.
compiler says:
Enter Your Expression
-5+3
Stack: [ ][ 5 ][ - ][ 3 ][ + ]
Exception in thread "main" java.lang.NumberFormatException: empty String
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:10 11)
at java.lang.Double.valueOf(Double.java:504)
at ExpressionParser.RPNtoDouble(ExpressionParser.java:160)
at ExpressionParser.main(ExpressionParser.java:194)*
I think it has something to do with the Double d1 = Double.valueOf( stack.pop() ); cause it still pops another two values, where I only need one for a solving a unary operator. any help?
public class ExpressionParser
{
// Associativity constants for operators
private static final int LEFT_ASSOC = 0;
private static final int RIGHT_ASSOC = 1;
// Operators
private static final Map<String, int[]> OPERATORS = new HashMap<String, int[]>();
static
{
// Map<"token", []{precendence, associativity}>
OPERATORS.put("-", new int[] { 0, LEFT_ASSOC });
OPERATORS.put("+", new int[] { 0, LEFT_ASSOC });
OPERATORS.put("*", new int[] { 5, LEFT_ASSOC });
OPERATORS.put("/", new int[] { 5, LEFT_ASSOC });
OPERATORS.put("_", new int[] { 5, RIGHT_ASSOC });
}
// Test if token is an operator
private static boolean isOperator(String token)
{
return OPERATORS.containsKey(token);
}
// Test associativity of operator token
private static boolean isAssociative(String token, int type)
{
if (!isOperator(token))
{
throw new IllegalArgumentException("Invalid token: " + token);
}
if (OPERATORS.get(token)[1] == type) {
return true;
}
return false;
}
// Compare precedence of operators.
private static final int cmpPrecedence(String token1, String token2)
{
if (!isOperator(token1) || !isOperator(token2))
{
throw new IllegalArgumentException("Invalid tokens: " + token1
+ " " + token2);
}
return OPERATORS.get(token1)[0] - OPERATORS.get(token2)[0];
}
// CONVERT UNARY OPERATORS
public static String[] unaryToexp(String[] inputTokens)
{
ArrayList<String> out = new ArrayList<String>();
Stack<String> stack = new Stack<String>();
//if token is an unary minus
for (String token : inputTokens)
{
if( ((token == "-") && (isOperator(stack.peek()) || stack.empty() ))){ //
token = "_";
}
else if (token == "-"){
token = "-";
}
out.add(token);
while (!stack.empty())
{
out.add(stack.pop());
}
}
String[] output = new String[out.size()];
return out.toArray(output);
}
// Convert infix expression format into reverse Polish notation
public static String[] expToRPN(String[] inputTokens)
{
ArrayList<String> out = new ArrayList<String>();
Stack<String> stack = new Stack<String>();
// For each token
for (String token : inputTokens)
{
// If token is an operator
if (isOperator(token))
{
// While stack not empty AND stack top element
// is an operator
while (!stack.empty() && isOperator(stack.peek()))
{
if ((isAssociative(token, LEFT_ASSOC) &&
cmpPrecedence(token, stack.peek()) <= 0) ||
(isAssociative(token, RIGHT_ASSOC) &&
cmpPrecedence(token, stack.peek()) < 0))
{
out.add(stack.pop());
continue;
}
break;
}
// Push the new operator on the stack
stack.push(token);
}
// If token is a left bracket '('
else if (token.equals("("))
{
stack.push(token); //
}
// If token is a right bracket ')'
else if (token.equals(")"))
{
while (!stack.empty() && !stack.peek().equals("("))
{
out.add(stack.pop());
}
stack.pop();
}
// If token is a number
else
{
out.add(token);
}
}
while (!stack.empty())
{
out.add(stack.pop());
}
String[] output = new String[out.size()];
return out.toArray(output);
}
public static double RPNtoDouble(String[] tokens)
{
Stack<String> stack = new Stack<String>();
// For each token
for (String token : tokens)
{
// If the token is a value push it onto the stack
if (!isOperator(token))
{
stack.push(token);
}
else
{
// Token is an operator: pop top two entries
Double d2 = Double.valueOf( stack.pop() );
Double d1 = Double.valueOf( stack.pop() );
//Get the result
Double result = token.compareTo("_") == 0 ? d2 * -1 :
token.compareTo("*") == 0 ? d1 * d2 :
token.compareTo("/") == 0 ? d1 / d2 :
token.compareTo("+") == 0 ? d1 + d2 :
d1 - d2;
// Push result onto stack
stack.push( String.valueOf( result ));
}
}
return Double.valueOf(stack.pop());
}
public static void main(String[] args) throws Exception{
Scanner in = new Scanner(System.in);
String reg = "((?<=[<=|>=|==|\\+|\\*|\\-|\\_|<|>|/|=])|(?=[<=|>=|==|\\+|\\*|\\-|<|>|/|=]))";
while(true){
//try{
System.out.println("Enter Your Expression");
//String[] input = "( 1 + 2 ) * ( 3 / 4 ) - ( 5 + 6 )".split(" ");
String[] input = in.nextLine() .split(reg);
String[] unary = unaryToexp(input); //.split(reg);
String[] output = expToRPN(unary);
// Build output RPN string minus the commas
System.out.print("Stack: ");
for (String token : output) {
System.out.print("[ ");System.out.print(token); System.out.print(" ]");
}
System.out.println(" ");
// Feed the RPN string to RPNtoDouble to give result
Double result = RPNtoDouble( output );
System.out.println("Answer= " + result);
//}catch (){
//System.out.println("INVALID EXPRESSION"); }
}
}
}
Here you are:
private static final ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
public static String eval(String matlab_expression){
if(matlab_expression == null){
return "NULL";
}
String js_parsable_expression = matlab_expression
.replaceAll("\\((\\-?\\d+)\\)\\^(\\-?\\d+)", "(Math.pow($1,$2))")
.replaceAll("(\\d+)\\^(\\-?\\d+)", "Math.pow($1,$2)");
try{
return engine.eval(js_parsable_expression).toString();
}catch(javax.script.ScriptException e1){
return null; // Invalid Expression
}
}
Couldn't you use the javascript scripting engine? (you would need a bit of tweaking for the 5--2 expression) The code below outputs:
3+2*1-6/3 = 3.0
3++2 = Invalid Expression
-5+2 = -3.0
5--2 = 7.0
Code:
public class Test1 {
static ScriptEngine engine;
public static void main(String[] args) throws Exception {
engine = new ScriptEngineManager().getEngineByName("JavaScript");
printValue("3+2*1-6/3");
printValue("3++2");
printValue("-5+2");
printValue("5--2");
}
private static void printValue(String expression) {
String adjustedExpression = expression.replaceAll("--", "- -");
try {
System.out.println(expression + " = " + engine.eval(adjustedExpression));
} catch (ScriptException e) {
System.out.println(expression + " = Invalid Expression");
}
}
}
Rather than re-invent the wheel you could use a parser generator such as JavaCC or antlr, which is specifically designed for this kind of task. This is a nice example of a simple expression parser and evaluator in a couple of dozen lines of JavaCC.
Take a look at some examples and try to find a rule how to distinguish negative values from operators.
A rule like:
if (token is + or -) and next token is a number
and
(the previous token was empty
or the prvious token was ')' or another operator)
then it is a sign to the current value.
You could iterate through your original token list and create a new token list based on this rules.
I have just written such an expression evaluator and have an iterator for tokenizing expressions at hand. plan to publish it after some extensions on GitHub.
EDIT: Here is the iterator, the references and calls should be clear, it is a bit more complex because of support for variables/functions and multi-character operators:
private class Tokenizer implements Iterator<String> {
private int pos = 0;
private String input;
private String previousToken;
public Tokenizer(String input) {
this.input = input;
}
#Override
public boolean hasNext() {
return (pos < input.length());
}
private char peekNextChar() {
if (pos < (input.length() - 1)) {
return input.charAt(pos + 1);
} else {
return 0;
}
}
#Override
public String next() {
StringBuilder token = new StringBuilder();
if (pos >= input.length()) {
return previousToken = null;
}
char ch = input.charAt(pos);
while (Character.isWhitespace(ch) && pos < input.length()) {
ch = input.charAt(++pos);
}
if (Character.isDigit(ch)) {
while ((Character.isDigit(ch) || ch == decimalSeparator)
&& (pos < input.length())) {
token.append(input.charAt(pos++));
ch = pos == input.length() ? 0 : input.charAt(pos);
}
} else if (ch == minusSign
&& Character.isDigit(peekNextChar())
&& ("(".equals(previousToken) || ",".equals(previousToken)
|| previousToken == null || operators
.containsKey(previousToken))) {
token.append(minusSign);
pos++;
token.append(next());
} else if (Character.isLetter(ch)) {
while (Character.isLetter(ch) && (pos < input.length())) {
token.append(input.charAt(pos++));
ch = pos == input.length() ? 0 : input.charAt(pos);
}
} else if (ch == '(' || ch == ')' || ch == ',') {
token.append(ch);
pos++;
} else {
while (!Character.isLetter(ch) && !Character.isDigit(ch)
&& !Character.isWhitespace(ch) && ch != '('
&& ch != ')' && ch != ',' && (pos < input.length())) {
token.append(input.charAt(pos));
pos++;
ch = pos == input.length() ? 0 : input.charAt(pos);
if (ch == minusSign) {
break;
}
}
if (!operators.containsKey(token.toString())) {
throw new ExpressionException("Unknown operator '" + token
+ "' at position " + (pos - token.length() + 1));
}
}
return previousToken = token.toString();
}
#Override
public void remove() {
throw new ExpressionException("remove() not supported");
}
}

Categories

Resources