I want to make a calculator that converts infix to postfix, using only strings and characters.
here's the requirements:
for i=1 to m:
if c_i is an operand: Transfer c_i to output.
-if c_i is a left parentheses: Push c_i to tmp.
-if c_i is a right parentheses: Pop elements from tmp and transfer
-them to output until a left-parentheses
-is met. Pop left-parentheses.
if c_i is an operator: Let the top tmp element be t. Pop and
-transfer elements from tmp to output
-until:
-p(t) < p(c_i) or
-t is a left-parentheses or
-tmp is empty.
-Push c_i to tmp.
static String infixToPostfix(String infix){
String postfix = "";
infix = readLine();
String temp ="";
String output ="";
for (int i=0 ; i<infix.length(); i++) {
if (infix.charAt(i) == '+') {
infix = postfix;
}
else if (infix.charAt(i) == '-') {
infix = postfix;
}
else if (infix.charAt(i) == '*') {
infix = postfix;
}
else if (infix.charAt(i) == '/') {
infix = postfix;
}
else if (infix.charAt(i) == '(') {
infix = temp ;
}
else if (infix.charAt(i) == ')') {
temp=postfix;
}
}
return postfix;
}
Your code seems to be incomplete. Here is my own method to convert an Infix String to Postfix. Hope it helps.
boolean chk = true;
for(int i=0; i<expression.length(); i++) {
char ch = expression.charAt(i);
//Conditions for generating postfix String
if(ch=='(') {
operator.push(ch);
chk=false;
}
else if(isDigit(ch)) {
if(!chk) {
postfix = postfix + " " + ch;
}
else {
postfix = postfix + ch;
}
chk=true;
}
else if(ch == '+' || ch=='-') {
if(operator.isEmpty()) {
operator.push(ch);
}
else if(operator.peep()=='/'|| perator.peep()=='*'||operator.peep()=='-') {
postfix = postfix + " " + operator.pop();
operator.push(ch);
}
else {
operator.push(ch);
}
chk = false;
}
else if(ch == '*' || ch == '/') {
if(operator.isEmpty()) {
operator.push(ch);
}
else if(operator.peep()=='+' || operator.peep()=='-') {
operator.push(ch);
}
else {
postfix = postfix + " " + operator.pop();
operator.push(ch);
}
chk = false;
}
else if(ch == ')') {
while(operator.peep()!='(') {
postfix = postfix + " " + operator.pop();
}
operator.pop();
}
}
while(!operator.isEmpty()) {
postfix = postfix + " " + operator.pop();
}
Related
private DSAQueue parseInfixToPostfix(String equation) {
String result = "";
char operator = ' ';
DSAStack stack = new DSAStack();
DSAQueue queue = new DSACircular();
for (int i = 0; i < equation.length(); i++) {
char c = equation.charAt(i);
if (Character.isLetterOrDigit(c)) {
result += c;
}
else if (c == '(') {
stack.push(c);
}
else if (c == ')') {
while (!stack.isEmpty() && stack.top() != '(') {
result += stack.pop();
}
if (!stack.isEmpty() && stack.top() != '(') {
result = "Invalid expression";
}
else {
stack.pop();
}
}
else { //when meets operator
while (!stack.isEmpty() && (precedenceOf(c) <= precedenceOf((char) stack.top()))) {
if (stack.top() == '(') {
result = "Invalid expression";
}
result += stack.pop();
}
stack.push(c);
}
}
while (!stack.isEmpty()) {
if (stack.top() == '(') {
result = "Invalid";
}
result += stack.pop();
}
queue.enqueue(result);
return queue;
}
Above is my code for converting infix to postfix. The example i used is "4+2" and what i got is:
Pushed: 43
Popped: 43
Enqueued: 4243
i dont know why it automatically converted "+" to 43, but i want to store the operator as the operator like "+" in the queue. Is it possible? Or is there an error? because i cant find out what the error is. thank you
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();
}
}
My program works fine, but I'm getting some irregular spaces in the output. For example, if the input is 44 * 5 + 6 the output is 44<2 spaces>5<1 space>*<1space>6<no space>+. I tried fiddling with all the lines of code that are adding to the String postfix, but to no avail. I'd like the output to be of the form: operand<1 space>operand<1 space>operator (i.e. 1 space between operands and operators."
Here's my code:
import java.util.*;
public class PostfixConversion {
public static void main(String args[]) {
System.out.print("Enter an expression: ");
String infix = new Scanner(System.in).nextLine();
String postfix = convertToPostfix(infix);
System.out.println(postfix);
//System.out.println("The result of calculation is: " + postfixEvaluate("23+"));
}
//converts infix expression into postfix expression
public static String convertToPostfix(String infixExp) {
String postFix = "The Postfix Expression is: ";
Stack<Character> stack = new Stack<Character>();
char character = ' ';
for(int i = 0; i < infixExp.length(); i++)
{
character = infixExp.charAt(i);
//determine if character is an operator
if(character == '*' || character == '-' || character == '/' || character == '+')
{
//postFix += " ";
while(!stack.empty() && precedence(stack.peek(), character))
postFix += stack.pop();
stack.push(character);
} else if(character == '(') {
stack.push(character);
} else if(character == ')') {
while(!stack.peek().equals('(') && !stack.isEmpty())
postFix += stack.pop();
if(!stack.isEmpty() && stack.peek().equals('('))
stack.pop(); // pop/remove left parenthesis
} else
postFix += character;
}
while(!stack.empty()) //add the remaining elements of stack to postfix expression
{
if(stack.peek().equals('('))
{
postFix = "There is no matching right parenthesis.";
return postFix;
}
postFix += stack.pop();
}
return postFix;
}
public static boolean precedence(char first, char second) {
int v1 = 0, v2 = 0;
//find value for first operator
if(first == '-' || first == '+')
v1 = 1;
else if(first == '*' || first == '/')
v1 = 2;
//find value for second operator
if(second == '-' || second == '+')
v2 = 1;
else if(second == '*' || second == '/')
v2 = 2;
if(v1 < v2)
return false;
return true;
}
First remove all whitespaces from input, so that they don't destroy your formatting:infixExp = infixExp.replaceAll("\\s",""); and then add whitespaces where needed.
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();
}