How to convert from infix to postfix without using any methods - java

We are supposed to write a program using the stack class that converts a string from infix to postfix using JOptionPane as the input method. We are supposed to do it all in one big for loop and one big tester file with no methods, I am not sure why. I am incredibly confused on how to do it but this is what I have so far. It crashes everytime I put something in.
import javax.swing.*;
import java.util.Stack;
public class InfixToPostfix
{
public static void main(String[] args)
{
JFrame f;
f = new JFrame();
String eq = JOptionPane.showInputDialog("Enter Equation");
StringBuilder postfix = new StringBuilder(new String(""));
Stack<Character> stack = new Stack<>();
int addSub = 0;
int multDiv = 0;
for(int i=0; i<eq.length(); i++)
{
char c = eq.charAt(i);
if(Character.isLetterOrDigit(c))
postfix.append(c);
else if(c=='(')
stack.push(c);
else if(c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
postfix.append(stack.pop());
stack.pop();
}
else
{
switch (c)
{
case '+':
case '-':
addSub = 1;
case '*':
case '/':
multDiv = 2;
}
while(!stack.isEmpty() && (addSub > multDiv || multDiv > addSub))
postfix.append(stack.pop());
stack.push(c);
}
while(!stack.isEmpty())
postfix.append(stack.pop());
}
JOptionPane.showMessageDialog(f, postfix.toString());
}
}

Related

Infix to Postfix Using Stacks - Java

I am trying to learn and implement some practical uses of stacks and I am doing a little program that takes in an equation and converts it to postfix notation. I am aware of how postfix notation, stacks and precedence works so the syntax approach I took seems to make sense to me however it seems to print it out in some sort of prefix notation with some duplicates at times, its really odd. Any help would be appreciated and I'll leave all of my code for you guys below, thank you.
import java.util.Scanner;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
infixToPostfix();
}
private static int Precedence(char character) {
System.out.print("" + character);
switch (character) {
case '+':
case '-':
return 1;
case '/':
case '*':
return 2;
case '^':
return 3;
}
return -1;
}
private static String infixToPostfix() {
Scanner scanner = new Scanner(System.in);
Stack<Character> operatorStack = new Stack<>();
System.out.println("please enter your equation");
String equation = scanner.nextLine();
StringBuilder result = new StringBuilder();
for (int i = 0; i < equation.length(); i++) {
char ch = equation.charAt(i);
if (Character.isDigit(ch)) {
result.append(ch);
} else if (ch == '(') {
operatorStack.push(ch);
} else if (operatorStack.isEmpty()
&& !Character.isDigit(ch)) {
operatorStack.push(ch);
} else {
while (!operatorStack.isEmpty()) {
if (!Character.isDigit(ch)
&& Precedence(
ch) < operatorStack
.peek()) {
result.append(operatorStack.pop());
} else if (!Character.isDigit(ch)
&& Precedence(
ch) > operatorStack
.peek()) {
operatorStack.push(ch);
} else if (ch == ')') {
result.append(operatorStack.pop());
}
}
}
}
System.out.println(result);
return result.toString();
}
}
2*(3+1) // input
++23(*1 // output
31+2* // expected output
Process finished with exit code 0

Experiencing issues with overwriting previous instance of ArrayList object initialization

EDIT: I may have fixed it by making the instance variable static? If so, why does this fix it? This was something my prof glossed over in my intro to OOP class, so I never really learned about it.
so, I'm not sure if I'm using terrible coding practice and just don't realize it, but I'm having a single crippling issue with my program, despite this one issue, everything appears to be running fine.
This program takes strings from an argument file and executes the commands based on the instructions. However, when I issue the command "x = x + 5" I experience a crippling issue.
My class titled Work creates another instance of my other class Read. When it does this, the ArrayList that I define at the top of Read is overwritten with a new instance, and thus, deletes the whole list of variables. I'm unable to find a way to make the initialization execute only once. Where am I going wrong?
Work:
import java.util.*;
public class Work {
static int Precedence(char ch){
switch (ch){
case '+':
case '-':
return 1;
case '*':
case '/':
case '%':
return 2;
case '^':
return 3;
}
return -1;
}
String infixConverter(String infix){
Variable tvar = new Variable(); //consider removing these~
Read reader = new Read();
String pfix = new String("");
Stack<Character> stack = new Stack<>();
for (int i=0; i<infix.length(); ++i) {
char curr = infix.charAt(i);
// if (Character.isLetterOrDigit(curr)||curr==' ') {
if (Character.isDigit(curr)||curr==' ') {
pfix += curr;
}
else if (Character.isLetter(curr)){
// Read reader = new Read();
if (reader.varExists(curr)){
// Variable tvar = new Variable();
int n = reader.getIndex(curr);
tvar = reader.vars.get(n);
pfix += tvar.getValue();
}
else{
//error
}
//implement this below
//check for letter within the string, if the string is
}
else if (curr == '('){
stack.push(curr);
}
else if (curr == ')'){
while (!stack.isEmpty() && stack.peek() != '(') {
pfix += stack.pop();
}
if (!stack.isEmpty() && stack.peek() != '(') {
return "Invalid Expression"; // invalid expression
}
else {
stack.pop();
}
}
else {
while (!stack.isEmpty() && Precedence(curr) <=
Precedence(stack.peek())) {
pfix += stack.pop();
}
stack.push(curr);
}
}
while (!stack.isEmpty()) {
pfix += stack.pop();
}
int sol = postfixEvaluation(pfix);
pfix = Integer.toString(sol);
return pfix;
}
Integer postfixEvaluation(String pfix){
Stack<Integer> stack = new Stack<>();
for(int i = 0; i < pfix.length(); i++){
char curr = pfix.charAt(i);
if(curr == ' '){
continue;
}
else if(Character.isDigit(curr)){
int num = 0;
while(Character.isDigit(curr)){
num = num*10 + (int)(curr-'0');
i++;
if (i==pfix.length()){break;}
curr = pfix.charAt(i);
}
i--;
stack.push(num);
//include variables and be able to insert them into here
}
else{
int val1 = stack.pop();
int val2 = stack.pop();
switch(curr){
case '+':
stack.push(val2+val1);
break;
case '-':
stack.push(val2-val1);
break;
case '/':
stack.push(val2/val1);
break;
case '%':
stack.push(val2%val1);
break;
case '*':
stack.push(val2*val1);
break;
}
}
}
return stack.pop();
}
}
Read:
import java.util.*;
public class Read {
ArrayList<Variable> vars = new ArrayList<Variable>();//FIX THIS SHIT AHHHHHHHHH
Variable tempvar = new Variable();
Work eval = new Work();
private int lnNum = 1;
private String arg="";
public void thing() {
String thing,thing2;
if (arg.contains("print")){
String real="";
int i = arg.indexOf('t');
if (i!=4){}//error
thing = arg.substring(0,i);
if (thing!="print"){}//error
thing2 = arg.substring(i+2,arg.length());
real = eval.infixConverter(thing2);
System.out.println(real);
}
else if (arg.contains("read")){
Scanner in = new Scanner(System.in);
int i = arg.indexOf('d');
if (i!=3){}//error
thing = arg.substring(0,i+1);
if (thing!="read"){}//error
thing2 = arg.substring(i+2,arg.length());
char c2 = thing2.charAt(0);
if (thing2.length()>1){}//error
System.out.println("Enter a value for "+thing2+": ");
String vv = in.nextLine();
vv = eval.infixConverter(vv);
int vvv = Integer.parseInt(vv);
tempvar.setValue(c2, vvv);
vars.add(tempvar);
}
else if (arg.contains("=")){
int i = arg.indexOf('=');
int tempval;
thing = arg.substring(0,i-1);
thing2 = arg.substring(i+2,arg.length());
if(thing.length()>1){}//error
thing2=eval.infixConverter(thing2);
char c = thing.charAt(0);
if (vars.contains(thing)){
tempval = Integer.parseInt(thing2);
tempvar.setValue(c,tempval);
int f = vars.indexOf(thing);
}
else if(Character.isLetter(c)){
tempval = Integer.parseInt(thing2);
tempvar.setValue(c,tempval);
vars.add(tempvar);
}
else{
//error
}
}
else{
}
}
boolean varExists(char c){
for (int i = 0; i<vars.size(); i++){
tempvar = vars.get(i);
if (tempvar.getTitle()==c){
return true;
}
}
return false;
}
int getIndex(char c) {
for (int i = 0; i <= vars.size(); i++) {
tempvar = vars.get(i);
if (tempvar.getTitle() == c) {
return i;
}
}
return -1;
}
int inLineNum(){
lnNum++;
return lnNum;
}
void setArg(String c){
arg=c;
}
}

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();
}

Calculate negatives in the stack calculator

Bear with me, I'm a little fried right now from getting this all together, but I'm at the final stretch. I've made a calculator in java that takes an infix equation and then changes it to postfix. It also takes variables! I'm made it so my postfix includes negative numbers from infix. This would look like so:
infix: 1+-2*(4/2)
postfix: 12_42/*+
So obviously I got it working where negatives are '_' in postfix. Cool yeah? Ok, but now I gotta get my calculator to read them and I'm just getting brain-fart on where it goes on the stack and what I do to make it work without making a condition for all forms of operands. Here is what I have:
import java.util.Stack;
/**
*
* #author rtibbetts268
*/
public class InfixToPostfix
{
/**
* Operators in reverse order of precedence.
*/
private static final String operators = "-+/*_";
private static final String operands = "0123456789x";
/*public int evalInfix(String infix)
{
return evaluatePostfix(convert2Postfix(infix));
}*/
public String xToValue(String postfixExpr, String x)
{
char[] chars = postfixExpr.toCharArray();
StringBuilder newPostfixExpr = new StringBuilder();
for (char c : chars)
{
if (c == 'x')
{
newPostfixExpr.append(x);
}
else
{
newPostfixExpr.append(c);
}
}
return newPostfixExpr.toString();
}
public String convert2Postfix(String infixExpr)
{
char[] chars = infixExpr.toCharArray();
StringBuilder in = new StringBuilder(infixExpr.length());
for (int i = 0; i<chars.length; i++)
{
if (infixExpr.charAt(i) == '-')
{
if (i == 0)
{
in.append('_');
}
else if(isOperand(infixExpr.charAt(i + 1)))
{
if (i != infixExpr.length())
{
if (isOperator(infixExpr.charAt(i-1)))
in.append('_');
}
else
{
in.append(infixExpr.charAt(i));
}
}
else
{
in.append(infixExpr.charAt(i));
}
}
else
{
in.append(infixExpr.charAt(i));
}
}
chars = in.toString().toCharArray();
Stack<Character> stack = new Stack<Character>();
StringBuilder out = new StringBuilder(in.toString().length());
for (char c : chars)
{
if (isOperator(c))
{
while (!stack.isEmpty() && stack.peek() != '(')
{
if (operatorGreaterOrEqual(stack.peek(), c))
{
out.append(stack.pop());
}
else
{
break;
}
}
stack.push(c);
}
else if (c == '(')
{
stack.push(c);
}
else if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
{
out.append(stack.pop());
}
if (!stack.isEmpty())
{
stack.pop();
}
}
else if (isOperand(c))
{
out.append(c);
}
}
while (!stack.empty())
{
out.append(stack.pop());
}
return out.toString();
}
public int evaluatePostfix(String postfixExpr)//YBEYFCNUNKJKDV IT'S RIGHT HERE!!!
{
char[] chars = postfixExpr.toCharArray();
Stack<Integer> stack = new Stack<Integer>();
for (char c : chars)
{
if (isOperand(c))
{
stack.push(c - '0'); // convert char to int val
}
else if (isOperator(c))
{
int op1 = stack.pop();
int op2 = stack.pop();
int result;
switch (c) {
case '_':
result = op1 * -1;
//stack.push(result);
//break;
case '*':
result = op1 * op2;
stack.push(result);
break;
case '/':
result = op2 / op1;
stack.push(result);
break;
case '+':
result = op1 + op2;
stack.push(result);
break;
case '-':
result = op2 - op1;
stack.push(result);
break;
}
}
}
return stack.pop();
}
private int getPrecedence(char operator)
{
int ret = 0;
if (operator == '-' || operator == '+')
{
ret = 1;
}
else if (operator == '*' || operator == '/')
{
ret = 2;
}
if (operator == '_')
{
ret = 3;
}
return ret;
}
private boolean operatorGreaterOrEqual(char op1, char op2)
{
return getPrecedence(op1) >= getPrecedence(op2);
}
private boolean isOperator(char val)
{
return operators.indexOf(val) >= 0;
}
private boolean isOperand(char val)
{
return operands.indexOf(val) >= 0;
}
}
I would post less, but it all tends to work cohesively so I'll explain. Look closely at the method called evaluatePostfix() (it's the third one from the top).
This is where the class can take a postfix expression such as the one I named above and calculates it. It calculates an expression with all positive integers, but when I tried to implement it to change a number to negative before it actually ran any of the math, it goes kaputt.
Could anyone assist me with fixing this specific method so it works? I need it to calculate negative integers as well of positive.
Basically the problem is in trying to pop from an empty stack for the '_' case. What you need to do is only attempt to pop op2 from the stack for the '*/+-' cases and not the '_' case.
public int evaluatePostfix(String postfixExpr)
{
char[] chars = postfixExpr.toCharArray();
Stack<Integer> stack = new Stack<Integer>();
for (char c : chars)
{
if (isOperand(c))
{
stack.push(c - '0'); // convert char to int val
}
else if (isOperator(c))
{
int op1 = stack.pop();
int op2;
int result;
switch (c) {
case '_':
result = op1 * -1;
stack.push(result);
break;
case '*':
op2 = stack.pop();
result = op1 * op2;
stack.push(result);
break;
case '/':
op2 = stack.pop();
result = op2 / op1;
stack.push(result);
break;
case '+':
op2 = stack.pop();
result = op1 + op2;
stack.push(result);
break;
case '-':
op2 = stack.pop();
result = op2 - op1;
stack.push(result);
break;
}
}
}
return stack.pop();
}

How to calculate expression in java?

How to calculate user given Expression in java.
E:g, if the given exp is 3*4+(5*6)
how to calculate this. can anyone help me out.
I found this code after a quick google:
import java.util.Stack;
/**
* Class to evaluate infix and postfix expressions.
*
* #author Paul E. Davis (feedback#willcode4beer.com)
*/
public class InfixPostfixEvaluator {
/**
* Operators in reverse order of precedence.
*/
private static final String operators = "-+/*";
private static final String operands = "0123456789";
public int evalInfix(String infix) {
return evaluatePostfix(convert2Postfix(infix));
}
public String convert2Postfix(String infixExpr) {
char[] chars = infixExpr.toCharArray();
Stack<Character> stack = new Stack<Character>();
StringBuilder out = new StringBuilder(infixExpr.length());
for (char c : chars) {
if (isOperator(c)) {
while (!stack.isEmpty() && stack.peek() != '(') {
if (operatorGreaterOrEqual(stack.peek(), c)) {
out.append(stack.pop());
} else {
break;
}
}
stack.push(c);
} else if (c == '(') {
stack.push(c);
} else if (c == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
out.append(stack.pop());
}
if (!stack.isEmpty()) {
stack.pop();
}
} else if (isOperand(c)) {
out.append(c);
}
}
while (!stack.empty()) {
out.append(stack.pop());
}
return out.toString();
}
public int evaluatePostfix(String postfixExpr) {
char[] chars = postfixExpr.toCharArray();
Stack<Integer> stack = new Stack<Integer>();
for (char c : chars) {
if (isOperand(c)) {
stack.push(c - '0'); // convert char to int val
} else if (isOperator(c)) {
int op1 = stack.pop();
int op2 = stack.pop();
int result;
switch (c) {
case '*':
result = op1 * op2;
stack.push(result);
break;
case '/':
result = op2 / op1;
stack.push(result);
break;
case '+':
result = op1 + op2;
stack.push(result);
break;
case '-':
result = op2 - op1;
stack.push(result);
break;
}
}
}
return stack.pop();
}
private int getPrecedence(char operator) {
int ret = 0;
if (operator == '-' || operator == '+') {
ret = 1;
} else if (operator == '*' || operator == '/') {
ret = 2;
}
return ret;
}
private boolean operatorGreaterOrEqual(char op1, char op2) {
return getPrecedence(op1) >= getPrecedence(op2);
}
private boolean isOperator(char val) {
return operators.indexOf(val) >= 0;
}
private boolean isOperand(char val) {
return operands.indexOf(val) >= 0;
}
}
From: http://willcode4beer.com/design.jsp?set=evalInfix
Take a look at Java Expression evaluator: http://java.net/projects/eval/pages/Home
Java does this already. No need to download anything.
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class EvaluationExample {
public static void main(String[] args) throws Exception{
System.out.println(new ScriptEngineManager().getEngineByName("JavaScript").eval("3*4+(5*6)"));
}
}
(This is not the first SO answer to show how to use scripting in Java. I only added it here in case people looking at this page do not follow the links. Parsing is fun, and valuable to study, but if you just need to evaluate user-supplied expressions, use a script.)
UPDATE The OP is looking for a postfix evaluation solution. This has to be done in two steps: first convert the input string into postfix notation, then run the postfix "code" through a (presumably stack-based evaluator). See PaulPRO's answer for this. If you are willing to use JavaCC or another parser generator, you can be much more flexible with the strings you accept, allowing newlines and other whitespace.
Here's a spoiler (Mathematical Expression Parse in Java).

Categories

Resources