RPN Problems (Order of Operations) [closed]
I'm trying to make a simple calculator with order of operations. I had read in the Internet and found the algorithm of RPN (Reverse Polish notation).
EDIT:
Lets take an example: 2 * 5 - 3 + 4
Ok, I did as you both said check it out now开发者_运维问答:
Proc is string array of both numbers and operations. Proc will be {2, *, 5, -, 3, +, 4}
This is the code:
int tempt = 0;
Stack <Double> stc = new Stack <Double>();
while (tempt < proc.length)
{
try
{
Double num = Double.parseDouble(proc[tempt]);
stc.push(num);
tempt++;
}
catch (Exception e)
{
char [] stcs = proc[tempt].toCharArray();
switch (stcs[0])
{
case '+':
{
double a2 = stc.pop();
double a1 = stc.pop();
stc.push(a1 + a2);
tempt++;
break;
}
case '-':
{
double a2 = stc.pop();
double a1 = stc.pop();
stc.push(a1 - a2);
tempt++;
break;
}
case 'x':
{
double a2 = stc.pop();
double a1 = stc.pop();
stc.push(a1 * a2);
tempt++;
break;
}
case '÷':
{
double a2 = stc.pop();
double a1 = stc.pop();
stc.push(a1 / a2);
tempt++;
break;
}
}
}
STILL DOESNT WORK
How can I make it work as well? HELP ME PLS!
You've got the algorithm wrong. 2 * 5 - 3 + 4
in RPN translates to: 2 5 * 3 - 4 +
. I don't know why you are treating numbers and symbols independently in two separate lists: in Reverse Polish notation:
2 3 + 4 * === (2 + 3) * 4
while
2 3 4 + * === 2 * (3 + 4)
That being said your program is almost correct except that for input you should take a series of symbols (both values and operators). Now you read symbols from left to right. If it is a number, push it onto the stack. If operator: pop top two values and push the result. That's it!
UPDATE: Example
Input: 2 5 * 3 - 4 +
Stack: []
Iteration I: (reading 2
from input)
Input: 5 * 3 - 4 +
Stack: [2]
Iteration II: (reading 5
from input)
Input: * 3 - 4 +
Stack: [2, 5]
Iteration III: (reading *
from input)
Input: 3 - 4 +
Stack: [2 * 5]
== [10]
Iteration IV: (reading 3
from input)
Input: - 4 +
Stack: [10, 3]
Iteration V: (reading -
from input)
Input: 4 +
Stack: [10 - 3]
== [7]
Iteration VI: (reading 4
from input)
Input: +
Stack: [7, 4]
Iteration VII: (reading +
from input)
Input: ``
Stack: [7 + 4]
== [11]
Result: 11
(no further input, one and only element on the stack is the result)
UPDATE 2: C'mon!
You are writing a program to interpret RPN but you are feeding it with infix notation! Try with this input:
String[] proc = new String[]{"2", "5", "x", "3", "-", "4", "+"};
There are several other flaws in your code (duplication, exception driven flow control, no error handling), but essentially with this input it should work.
精彩评论