java - Evaluate Postfix Using Stack -
i trying create program evaluates postfix expression.for example "3500 43 12 * 47 2 / + -" .here code
public static int evaluatepostfixexpression(string postfixexpr){ stack s = new stack(); int result = 0; string operand = null; for(int = 0; i<postfixexpr.length();i++){ if(character.isdigit(postfixexpr.charat(i)) == true){ operand = operand + postfixexpr.charat(i); if(character.isdigit(postfixexpr.charat(i+1)) == false){ s.push(operand); operand = null; } } if(postfixexpr.charat(i) == '+'){ result = result + integer.parseint((string) s.pop()) + integer.parseint((string) s.pop()) ; } if(postfixexpr.charat(i) == '-'){ result = result + integer.parseint((string) s.pop()) - integer.parseint((string) s.pop()) ; } if(postfixexpr.charat(i) == '*'){ result = result + integer.parseint((string) s.pop()) * integer.parseint((string) s.pop()) ; } if(postfixexpr.charat(i) == '/'){ result = result + integer.parseint((string) s.pop()) / integer.parseint((string) s.pop()) ; } } return result; } //end-evaluatepostfixexpression
when try run it, there occurs error.
exception in thread "main" java.lang.numberformatexception: input string: "null12" @ java.lang.numberformatexception.forinputstring(unknown source) @ java.lang.integer.parseint(unknown source) @ java.lang.integer.parseint(unknown source)
i can't find solution.it great if help.
edit: handled errors , code works;
public static int evaluatepostfixexpression(string postfixexpr){ stack s = new stack(); int result = 0; string operand = ""; for(int = 0; i<postfixexpr.length();i++){ if(character.isdigit(postfixexpr.charat(i)) == true){ operand = operand + postfixexpr.charat(i); if(character.isdigit(postfixexpr.charat(i+1)) == false){ s.push(operand); operand = ""; } } if(postfixexpr.charat(i) == '+'){ int x = integer.parseint((string) s.pop()) + integer.parseint((string) s.pop()); result = result + x ; s.push(string.valueof(x)); } if(postfixexpr.charat(i) == '-'){ int x = integer.parseint((string) s.pop()) - integer.parseint((string) s.pop()); result = result + x ; s.push(string.valueof(x)); } if(postfixexpr.charat(i) == '*'){ int x = integer.parseint("" + s.pop()) * integer.parseint("" + s.pop()); result = result + x ; s.push(string.valueof(x)); } if(postfixexpr.charat(i) == '/'){ int x = integer.parseint((string) s.pop()) / integer.parseint((string) s.pop()); result = result + x ; s.push(string.valueof(x)); } } return result; }
but result wrong.it should 2961 getting -1952.
try one:
string operand = "";
change when
if(character.isdigit(postfixexpr.charat(i+1)) == false){ s.push(operand); operand = ""; }
Comments
Post a Comment