I am attempting to create a RPN calculator using a Scanner. I am gathering numbers and operators from the user and concat the inputs onto a string called results
. Once they quit (by saying "Q" or "q"), I would like to pass results
to the method evaluateResults
, which would perform the operations they inputed. For example, if the string passed to evaluateResults
is '45+', I would like to add 4 and 5. However, if the the input is '456+x' I would like to perform '(4 + 5) x 6' , meaning I am reading the string until a character is an operator, then I perform that operator with the first two numeric characters of the string... I am attempting to do this with the following program:
import java.util.*;
/**
This calculator uses the reverse Polish notation.
*/
public class P15_7 {
public static void evaluateResult(String inp){
int output = 0;
Stack<Integer> results = new Stack<>();
for (int i = 0; i < inp.length(); i++){
char c = inp.charAt(i);
if (Character.isDigit(c)){
results.push(Character.getNumericValue(c));
}else{
Iterator<Integer> itr = results.iterator();
while(itr.hasNext()){
if (c == '+'){
int f = itr.next(); // Getting the First value of the Stack
itr.remove(); // Removing it (first val)
int s = itr.next(); // Getting the Second value of the Stack
itr.remove(); // Removing it (second val)
output = output + (f + s);// calculate
itr = results.iterator(); // Starting the iterator back at Index 0
itr.add(output); // Adding the calculated value at the start : Index 0
}else if (c == '-'){
int f = itr.next();
itr.remove();
int s = itr.next();
itr.remove();
output = output + (f - s);
itr = results.iterator();
itr.add(output);
}else if (c == '*' || c == 'x'){
int f = itr.next();
itr.remove();
int s = itr.next();
itr.remove();
output = output + (f * s);
itr = results.iterator();
itr.add(output);
}else if (c == '/'){
int f = itr.next();
itr.remove();
int s = itr.next();
itr.remove();
output = output + (f / s);
itr = results.iterator();
itr.add(output);
}
}
}
}
System.out.println("You answer is: " + output);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String results = "";
System.out.println("Enter one number or operator per line, Q to quit. ");
boolean done = false;
while(!done){
String input = in.nextLine();
if(input.equals("Q") || input.equals("q")){
evaluateResult(results);
done = true;
}else{
results = results.concat(input);
System.out.println(results);
}
}
}
}
The problem I am running into is that I can not get the int output
to get added at the start of the stack with the use of the iterator. How can I modify this code to perform the method how I have described it above? Any modifications will be helpful and please let me know if I am unclear about anything and I will clarify.