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();
}
}
Related
so I am in the middle of a data structures course and we have been tasked with making a recursive solution to a prefix (-+ABC) problem and converting it into a postfix (AB+C-) solution. I feel like I'm 70% there...just missing that little something.
The outputString is then returned and written to a .txt file. I know this part works due to past labs I have worked with.
The code provided returns BCBCABCBCBCABC+ABC when it should in theory return AB+C-
public static boolean operator(char o) {
return o == '+' || o == '-' || o == '*' || o == '/' || o == '$';
}
public static String preToPost(String s) {
char[] c = s.toCharArray();
// System.out.println(c);
char ch = c[0];
//System.out.println(ch);
char[] cMinusFront = new char[s.length() - 1];
for (int i = 0, k = 0; i < c.length; i++) {
if (i == 0) {
continue;
}
cMinusFront[k++] = c[i];
}
s = String.valueOf(cMinusFront);
System.out.println(s);
String a;
String b;
String outputString = null;
if (s.length() == 1) {
return outputString;
}
if (operator(ch)) {
a = preToPost(s);
} else {
a = s.substring(0, 0);
}
if (operator(ch)) {
b = preToPost(s);
} else {
b = s.substring(0, 0);
}
outputString = a;
outputString = outputString.concat(b);
outputString = outputString.concat(String.valueOf(cMinusFront));
return outputString;
}
Try this.
static boolean isOperator(char ch) {
return ch == '+' || ch == '-' || ch == '*' || ch == '/';
}
static String preToPost(StringReader input) throws IOException {
int ch = input.read();
if (ch == -1)
return "";
else if (isOperator((char)ch))
return preToPost(input) + preToPost(input) + (char)ch;
else
return "" + (char)ch;
}
static String preToPost(String input) throws IOException {
return preToPost(new StringReader(input));
}
public static void main(String[] args) throws IOException {
System.out.println(preToPost("*-+ABC"));
}
output:
AB+C-*
I am having problems getting my toString() method to work and print out parenthesis. Within my infix notation. For example, right now if I enter 12+3* it will print out 1 + 2 * 3. I would like it to print out ((1+2) *3).
Also, I would like my expression tree to be built when it contains a space within the input. For example, right now if I enter 12+ it works, but I want to be able to enter 1 2 + and it still work. Any thoughts?
P.S. Ignore my evaluate method I haven't implemented it yet!
// Java program to construct an expression tree
import java.util.EmptyStackException;
import java.util.Scanner;
import java.util.Stack;
import javax.swing.tree.TreeNode;
// Java program for expression tree
class Node {
char ch;
Node left, right;
Node(char item) {
ch = item;
left = right = null;
}
public String toString() {
return (right == null && left == null) ? Character.toString(ch) : "(" + left.toString()+ ch + right.toString() + ")";
}
}
class ExpressionTree {
static boolean isOperator(char c) {
if ( c == '+' ||
c == '-' ||
c == '*' ||
c == '/'
) {
return true;
}
return false;
}
// Utility function to do inorder traversal
public void inorder(Node t) {
if (t != null) {
inorder(t.left);
System.out.print(t.ch + " ");
inorder(t.right);
}
}
// Returns root of constructed tree for given
// postfix expression
Node constructTree(char postfix[]) {
Stack<Node> st = new Stack();
Node t, t1, t2;
for (int i = 0; i < postfix.length; i++) {
// If operand, simply push into stack
if (!isOperator(postfix[i])) {
t = new Node(postfix[i]);
st.push(t);
} else // operator
{
t = new Node(postfix[i]);
// Pop two top nodes
// Store top
t1 = st.pop(); // Remove top
t2 = st.pop();
// make them children
t.right = t1;
t.left = t2;
// System.out.println(t1 + "" + t2);
// Add this subexpression to stack
st.push(t);
}
}
// only element will be root of expression
// tree
t = st.peek();
st.pop();
return t;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
/*boolean keepgoing = true;
while (keepgoing) {
String line = input.nextLine();
if (line.isEmpty()) {
keepgoing = false;
} else {
Double answer = calculate(line);
System.out.println(answer);
}
}*/
ExpressionTree et = new ExpressionTree();
String postfix = input.nextLine();
char[] charArray = postfix.toCharArray();
Node root = et.constructTree(charArray);
System.out.println("infix expression is");
et.inorder(root);
}
public double evaluate(Node ptr)
{
if (ptr.left == null && ptr.right == null)
return toDigit(ptr.ch);
else
{
double result = 0.0;
double left = evaluate(ptr.left);
double right = evaluate(ptr.right);
char operator = ptr.ch;
switch (operator)
{
case '+' : result = left + right; break;
case '-' : result = left - right; break;
case '*' : result = left * right; break;
case '/' : result = left / right; break;
default : result = left + right; break;
}
return result;
}
}
private boolean isDigit(char ch)
{
return ch >= '0' && ch <= '9';
}
private int toDigit(char ch)
{
return ch - '0';
}
}
Why you use inorder()? root.toString() returns exactly what you want, "((1+2)*3)"
Spaces you can skip at start of loop:
for (int i = 0; i < postfix.length; i++) {
if (postfix[i] == ' ')
continue;
...
Change main like this.
Scanner input = new Scanner(System.in);
String postfix = input.nextLine();
char[] charArray = postfix.replace(" ", "").toCharArray();
Node root = constructTree(charArray);
System.out.println("infix expression is");
System.out.println(root);
I'm trying to convert a postfix into an infix. I have some code, but I'm not able to fix it. There may be a condition I am missing. Or my structure is not quite right.
Also since I am new to Java I may need some help with "Stack<Character>".
public static String postfixToInfix(String postfix) {
Stack<Character> stack = new Stack();
Stack<Character> backup = new Stack();
StringBuilder infix = new StringBuilder(postfix.length());
infix.append('(');
for (int i = 0; i < postfix.length(); i++) {
if (!isOperator(postfix.charAt(i))) {
stack.push(postfix.charAt(i));
} else {
if (stack.size() == 1 ) { //stack is 1
backup.push(postfix.charAt(i));
}
if (stack.size() == 0 && backup.size()%5 == 0) { //stack is 0
stack.push(backup.pop());
stack.push(backup.pop());
stack.push(backup.pop());
stack.push(backup.pop());
stack.push(backup.pop());
stack.push(postfix.charAt(i));
}
if (stack.size() >= 2) { //stack is > 1
char arg2 = stack.pop();
char arg1 = stack.pop();
backup.push(')');
backup.push(arg2);
backup.push(postfix.charAt(i));
backup.push(arg1);
backup.push('(');
}
}
}
while (!backup.empty()) { //only size 3
stack.push(backup.pop());
}
while (!stack.empty()) { //only size 3
backup.push(stack.pop());
}
while (!backup.isEmpty()) {
infix.append(backup.pop());
}
infix.append(')');
return infix.toString();
}
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^' || c == '(' || c == ')';
}
public static void main(String[] args) {
String infix1 = "(3-(7*2))";
String postfix1 = "372*-";
String infix2 = "((7+1)*((3-6)*(5-2)))";
String postfix2 = "71+36-52-**";
System.out.println(" postfix1: " + postfix1);
s = postfixToInfix(postfix1);
System.out.println("postfixToInfix(postfix1): " + s);
if (s.equals(infix1)) {
System.out.println(" Korrekt!");
} else {
System.out.println(" Nicht korrekt!");
}
System.out.println();
System.out.println(" postfix2: " + postfix2);
s = postfixToInfix(postfix2);
System.out.println("postfixToInfix(postfix2): " + s);
if (s.equals(infix2)) {
System.out.println(" Korrekt!");
} else {
System.out.println(" Nicht korrekt!");
}
System.out.println();
}
}
Output
postfix1: 372*-
postfixToInfix(postfix1): (3-(7*2))
Korrekt!
postfix2: 71+36-52-**
postfixToInfix(postfix2): ((5(-*2)()**)(3-6)(7+1))
Nicht korrekt!
Process finished with exit code 0
Instead of dealing with the parenthesis and everything as separate entries in the stack, you could use strings to simplify the process:
private static boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}
public static String postfixToInfix(String postfix) {
Stack<String> s = new Stack<String>();
for (char c : postfix.toCharArray()) {
if (isOperator(c)) {
String temp = s.pop();
s.push('(' + s.pop() + c + temp + ')');
} else {
s.push(String.valueOf(c));
}
}
return s.pop();
}
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, *, /, +]
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");
}
}