In: Computer Science
JAVA
Stack - Implementation.
You will be able to use the push, pop and peek of Stack concept. Post-Fix calculator - When an arithmetic expression is presented in the postfix form, you can use a stack to evaluate the expression to get the final value. For example: the expression 3 + 5 * 9 (which is in the usual infix form) can be written as 3 5 9 * + in the postfix. More interestingly, post form removes all parentheses and thus all implicit precedence rules.
Program Implementation Requirements
Use the stack concept to create a post-fix calculator. I will be using a test-harnessPreview the document to run your program. Please make sure it meets the requirements to be run by the test harness.
Test harness:
public class StackCalcTest {
public static void main(String[] args) {
StackCalc stackCalc = new StackCalc();
String[] values = {"3", "5", "9", "*", "+"};
for(int i = 0; i < 5; i++) {
stackCalc.stack.push(values[i]);
}
System.out.println(stackCalc.stack);
System.out.println(stackCalc.answer()); }}
import java.util.Stack;
public class StackCalc{
Stack<String> stack = null;
StackCalc(){
stack = new Stack<String>();
}
public double answer() {
Stack<String> temp = new Stack<String>();
String s = "";
while(!stack.isEmpty()) {
String k = stack.peek();
s = s + k;
temp.push(k);
stack.pop();
}
Stack<Double> postfix = new Stack<Double>();
for (int i = s.length()-1; i>=0; i--) {
char c = s.charAt(i);
if (Character.isDigit(c))
postfix.push((double) (c - '0'));
else {
double val1 = postfix.peek();
postfix.pop();
double val2 = postfix.peek();
postfix.pop();
switch (c) {
case '+':
postfix.push(val2 + val1);
break;
case '-':
postfix.push(val2 - val1);
break;
case '/':
postfix.push(val2 / val1);
break;
case '*':
postfix.push(val2 * val1);
break;
}
}
}
return postfix.peek();
}
}
****************************************************************************
public class StackCalcTest {
public static void main(String[] args) {
StackCalc stackCalc = new StackCalc();
String[] values = { "3", "5", "9", "*", "+" };
for (int i = 0; i < 5; i++) {
stackCalc.stack.push(values[i]);
}
System.out.println(stackCalc.stack);
System.out.println(stackCalc.answer());
}
}
***************************************************************************
SEE OUTPUT
Thanks, PLEASE COMMENT if there is any concern.