java - Postfix evaluation for multidigit numbers -
i programming postfix evaluator, , able correctly single digit number. need idea of how multiple digit number, current program evaluates 2 digit number different numbers.
here's code :
public class postfixevaluation { public static void main(string[] args) { string postfix = "23+79*-"; stack stack = new stack(); (int = 0; < postfix.length(); i++) { if (postfix.charat(i) == '+') { int v1 = stack.pop(); int v2 = stack.pop(); stack.push(v2 + v1); } else if (postfix.charat(i) == '-') { int v1 = stack.pop(); int v2 = stack.pop(); stack.push(v2 - v1); } else if (postfix.charat(i) == '*') { int v1 = stack.pop(); int v2 = stack.pop(); stack.push(v2 * v1); } else if (postfix.charat(i) == '/') { int v1 = stack.pop(); int v2 = stack.pop(); stack.push(v2 / v1); } else if (postfix.charat(i) == '^') { int v1 = stack.pop(); int v2 = stack.pop(); stack.push((int) math.pow(v2, v1)); } else { stack.push((int) postfix.charat(i) - 48); } } system.out.println(stack.pop()); } }
to able identify multi-digit numbers, there must separator symbol between 2 numbers.
for example, can use space separator symbol. tokens in postfix
space separated. example become "2 3 + 7 9 * -"
. should read 1 token @ time, not 1 character.
Comments
Post a Comment