Question

In: Computer Science

Hi it's the java stack to convert from infix to postfix If I want to fix...

Hi it's the java stack to convert from infix to postfix

If I want to fix this code to calculate each numbers not just displaying the numbers what should I do?

Would you help me to fix the result?

import java.util.Stack;
import java.util.Scanner;
class Main
{
//Function to return precedence
static int Prec(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;

case '*':
case '/':
return 2;

case '^':
return 3;
}
return -1;
}
static String infixToPostfix(String exp)
{
// initializing empty String for result
String result = new String("");
Stack<Character> stack = new Stack<>();
int i=0;
int len=exp.length();
for ( i = 0; i<len; ++i)
{
char c = exp.charAt(i);
if (Character.isLetterOrDigit(c))
result =result+ c;
else if (c == '(')
stack.push(c);
else if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
result =result+ stack.pop();
if (!stack.isEmpty() && stack.peek() != '(')
return "Invalid Expression";   
else
stack.pop();
}
else
{
//for operators
while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek()))
result =result+ stack.pop();
stack.push(c);
}
}
while (!stack.isEmpty())
result =result+ stack.pop();

return result;
}
public static void main(String[] args)
{
String exp = "(5+8)*(7-3)";
String exp2="6+7*(3+9)/2";
System.out.println("Infix "+exp);
System.out.println("Postfix "+infixToPostfix(exp));
System.out.println("Infix "+exp2);
System.out.println("Postfix "+infixToPostfix(exp2));
}
}

Solutions

Expert Solution

import java.util.Stack;
import java.util.Scanner;
class Main
{
//Function to return precedence
static int Prec(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;

case '*':
case '/':
return 2;

case '^':
return 3;
}
return -1;
}
// Method to evaluate value of a postfix expression
static int evaluatePostfix(String exp)

{

//create a stack

Stack<Integer> stack=new Stack<>();

int val3,val4,val5,val6;

// Scan all characters one by one

for(int i=0;i<exp.length();i++)

{

char c=exp.charAt(i);

// If the scanned character is an operand (number here),

// push it to the stack.

if(Character.isDigit(c))

stack.push(c - '0');

// If the scanned character is an operator, pop two

// elements from stack apply the operator

else

{

int val1 = stack.pop();

int val2 = stack.pop();

switch(c)

{

case '+':

val3=val1+val2;

stack.push(val3);

pos(stack,i+1,val3,exp);

break;

case '-':

val4=val2-val1;

stack.push(val4);

pos(stack,i+1,val4,exp);

break;

case '/':

val5=val2/val1;

stack.push(val5);

pos(stack,i+1,val5,exp);

break;

case '*':

val6=val1*val2;

stack.push(val6);

pos(stack,i+1,val6,exp);

break;

}

}

}

return stack.pop();   

}

static int pos(Stack<Integer> stack,int m ,int val3,String exp){

int r=0;

int[] arr= new int[100];

System.out.printf("\n");

while(!stack.isEmpty())

{

arr[r]=stack.pop();

r++;

}

for(int j=r-1;j>=0;j--)

{

System.out.print(" "+arr[j]);

}

for(int k=r-1;k>=0;k--)

{

stack.push(arr[k]);

arr[k]=0;

}

//System.out.println(val3);

for(int l=m;l<exp.length();l++) {

char c=exp.charAt(l);

System.out.print(" "+c);

}
System.out.printf("\n");

return 0;

}
static String infixToPostfix(String exp)
{
// initializing empty String for result
String result = new String("");
Stack<Character> stack = new Stack<>();
int i=0;
int len=exp.length();
for ( i = 0; i<len; ++i)
{
char c = exp.charAt(i);
if (Character.isLetterOrDigit(c))
result =result+ c;
else if (c == '(')
stack.push(c);
else if (c == ')')
{
while (!stack.isEmpty() && stack.peek() != '(')
result =result+ stack.pop();
if (!stack.isEmpty() && stack.peek() != '(')
return "Invalid Expression";   
else
stack.pop();
}
else
{
//for operators
while (!stack.isEmpty() && Prec(c) <= Prec(stack.peek()))
result =result+ stack.pop();
stack.push(c);
}
}
while (!stack.isEmpty())
result =result+ stack.pop();

return result;
}
public static void main(String[] args)
{
String exp = "(5+8)*(7-3)";
String exp2="6+7*(3+9)/2";
System.out.println("Infix:"+exp);
System.out.println("Postfix expression:"+infixToPostfix(exp));
System.out.println("postfix evaluation: "+evaluatePostfix(infixToPostfix(exp)));
System.out.printf("\n");
System.out.println("Infix:"+exp2);
System.out.println("Postfix expression:"+infixToPostfix(exp2));
System.out.println("postfix evaluation: "+evaluatePostfix(infixToPostfix(exp2)));
}
}

OUTPUT:

Infix:(5+8)*(7-3)
Postfix expression:58+73-*

13 7 3 - *

13 4 *

52
postfix evaluation: 52

Infix:6+7*(3+9)/2
Postfix expression:6739+*2/+

6 7 12 * 2 / +

6 84 2 / +

6 42 +

48
postfix evaluation: 48


Related Solutions

Write a java class program to convert from INFIX TO POSTFIX Using stack operations
Write a java class program to convert from INFIX TO POSTFIX Using stack operations
Convert an infix expression to its postfix representation in JAVA
Convert an infix expression to its postfix representation in JAVA
java Convert the following Infix expression to a Postfix expression. Show all work                            Infix Expres
java Convert the following Infix expression to a Postfix expression. Show all work                            Infix Expression                                                 Stack                             Postfix Expression ---------------------------------------------------------------------------------------------------------------------------- 8 - 9*(2 + 1/4) + 3*7                                                     (empty)                            (blank) Evaluate the following Postfix expression. Once again, show all work.            Postfix                                               Stack                     Result           ---------------------------------------    --------------------    --------------            2 7 + 12 4 / * 8 5 + -
2. Convert the following infix form expression into the postfix form expression by using a stack:...
2. Convert the following infix form expression into the postfix form expression by using a stack: A+(B*(C-D)+E)/F-G*H Show the stack after each push/pop.
* the Algorithm: * write a java program to convert infix to postfix create(OpStk) OpStk.push("#") token...
* the Algorithm: * write a java program to convert infix to postfix create(OpStk) OpStk.push("#") token = nextToken() while (token != "#") if (token is an operand) append token to postfix expression else if (token is "(") // Left paren - Start of sub-expr OpStk.push( token ) else if (token is ")") // Right paren - End of sub-expr pop operators off the stack and append to the postfix expression - stop when you've popped a "(" else (token is...
this is my code I want the opposite i want to convert a postfix expression to...
this is my code I want the opposite i want to convert a postfix expression to infix expression #include <iostream> #include <string> #define SIZE 50 using namespace std; // structure to represent a stack struct Stack {   char s[SIZE];   int top; }; void push(Stack *st, char c) {   st->top++;   st->s[st->top] = c; } char pop(Stack *st) {   char c = st->s[st->top];   st->top--;   //(A+B)*(C+D)   return c; } /* function to check whether a character is an operator or not. this function...
Introduced to data structure using java 2)One of the applications of stack is to convert infix...
Introduced to data structure using java 2)One of the applications of stack is to convert infix expressions to postfix. Given the following infix expression, use the stack method to convert it to postfix. Show your work. x - y / (a + b) + z 3)write a generic method to find the maximum of three variables of generic type (i.e. type T). Note that you must use the compareTo method to compare the values. Also, the code must return one...
(Convert infix to postfix) Note: Postfix notation is a way of writing expression without using parentheses....
(Convert infix to postfix) Note: Postfix notation is a way of writing expression without using parentheses. For example, the expression ( 11 + 12 ) * 13 would be written as 11 12 + 13 * Assume that ALWAYS there is a space between operands and operators in the input expression. Use two stacks, one to store the operands and one to store the operators. Your program only accpets following operators : ( ) + - / * Write a...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix...
Using a stack, write a program that turns a simple infix arithmetic expression into a postfix expression. For example, 1 + 2 * 3 becomes 2 3 * 1 +. Also, evaluate the expression to ensure the expression is correct.
I need an infix to postfix function that accounts for all (, ), {, }, [,...
I need an infix to postfix function that accounts for all (, ), {, }, [, ].. For example. 8-{{(1-[0+4]+8)}} In c++ please.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT