I am currently building a Reverse Polish Notation Calculator in Java. I have written code so that that when "d" is entered, it prints the numbers on the stack. However, the numbers printed are then unusable for further calculations going forward (See image below).
Whereas, I want the numbers, once printed, to then be usable on the command line, so that I could do the following calculation.
This is my code for that particular part of the calculator so far:
import java.io.*;
import java.util.Arrays;
import java.util.Stack;
public class SRPN {
private Stack<Integer> stack = new Stack<>();
public void processCommand(String input) {
if(input.equals("+")) {
long n1 = stack.pop();
long n2 = stack.pop();
long result = n1 + n2;
if(result > Integer.MAX_VALUE) {
result = Integer.MAX_VALUE;
}
else if(result < Integer.MIN_VALUE) {
result = Integer.MIN_VALUE;
}
stack.push((int)result);
}
else if (input.equals("-")) {
long n1 = stack.pop();
long n2 = stack.pop();
long result = n2 - n1;
if(result > Integer.MAX_VALUE) {
result = Integer.MAX_VALUE;
}
else if(result < Integer.MIN_VALUE) {
result = Integer.MIN_VALUE;
}
stack.push((int)result);
}
else if (input.equals("*")) {
int n1 = stack.pop();
int n2 = stack.pop();
int result = n1 * n2;
if(result > Integer.MAX_VALUE) {
result = Integer.MAX_VALUE;
}
else if(result < Integer.MIN_VALUE) {
result = Integer.MIN_VALUE;
}
stack.push((int)result);
}
else if (input.equals("%")) {
int n1 = stack.pop();
int n2 = stack.pop();
int result = n1 % n2;
stack.push((int)result);
}
else if (input.equals("/")) {
double n1 = stack.pop();
double n2 = stack.pop();
double result = n2 / n1;
stack.push((int)result);
}
else if (input.equals("d")) {
String values = Arrays.toString(stack.toArray());
System.out.println(values);
}
else if (input.contentEquals("=")) {
System.out.println(stack.peek());
}
else // assume it's a number
{
stack.push(Integer.valueOf(input));
}
}
I just cant work out how you get the printed stack numbers to be usable.
Expected output would be that d prints the numbers entered to the stack:
1234 2345 3456 d 1234 2345 3456 d + 1234 5801 d + 7035
(as you can see above, d prints the first three entered numbers, then d + displays the 1234, adds the last two numbers of the stack, 2345 and 3456 together to get 5801, the next d + then adds 1234 and 5801 to get 7035)
Appreciate any help / tips, thank you!
I think you're just saying that instead of doign this:
System.out.println(values)
you want to print each number on its own line. If so, you just do this:
for n in values:
System.out.println(n)
So instead of printing:
[1234, 2345, 3456]
you'll print:
1234
2345
3456