Question
Java please

5. Using the following postfix expressions, use a class) to stack (or the method we used in (12 pts-6 eaeh) solve them producing a final result. (a) 69 5 725 7*+-18 25 5,2025 20%+ (b) 2 3+ 5-6 78+ 45 5 % 12 3/++ -
0 0
Add a comment Improve this question Transcribed image text
Answer #1

§子 25 5 兵nal result 3 5 35 6161 45 20 끄358 5 61 5- 5 マ+3 56 , , e62- Fin ves 12 -66 -66 62 0-66 12 45 /.5 -66

code:

import java.util.Stack;

public class Test

{

public static boolean isNumeric(String str)  

{  

try{

double d = Double.parseDouble(str);  

}  

catch(NumberFormatException nfe){  

return false;  

}  

return true;  

}

public static int evaluatePf(String expression)

{

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

String[] ops=expression.split(" ");

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

{

String c=ops[i];

// push to the stack when it is a number,

if(Test.isNumeric(c))

stack.push(Integer.parseInt(c));

// when it is an operator, pop the top two elements and apply the operator and push the result again

else

{

int v1 = stack.pop();

int v2 = stack.pop();

switch(c)

{

case "+":

stack.push(v2+v1);

break;

case "-":

stack.push(v2- v1);

break;

case "/":

stack.push(v2/v1);

break;

case "*":

stack.push(v2*v1);

break;

case "%":

stack.push(v2%v1);

break;

}

}

}

return stack.pop();

}

public static void main(String[] args)

{

String expression="69 5 7 25 7 * + - 18 25 5 / 20 25 20 % + * + + +";

System.out.println(evaluatePf(expression));

}

}

Add a comment
Know the answer?
Add Answer to:
Java please 5. Using the following postfix expressions, use a class) to stack (or the method...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT