- #1
schapman22
- 74
- 0
Homework Statement
I need to write a program that evaluates a postfix notation expression using a stack.
Homework Equations
5 3 2 * + 4 - 5 + = 12
The Attempt at a Solution
Code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.colorado.collections;
import java.util.Scanner;
/**
*
* @author schapman2344
*/
public class PostfixEvaluation
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
ArrayStack<Double> numbers = new ArrayStack();
String input;
double num1, num2, num3;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an expression in postfix notation" +
" then press <Enter>: ");
input = keyboard.next();
int i = 0;
do
{
if(Character.isWhitespace(input.charAt(i)))
i++;//go to next character
else if(Character.isDigit(input.charAt(i)))
{
numbers.push((double)input.charAt(i));
i++;
}
else
{
switch(input.charAt(i))
{
case '*':
num2 = numbers.pop();
num1 = numbers.pop();
num3 = num1*num2;
numbers.push(num3);
break;
case '/':
num2 = numbers.pop();
num1 = numbers.pop();
num3 = num1/num2;
numbers.push(num3);
break;
case '+':
num2 = numbers.pop();
num1 = numbers.pop();
num3 = num1+num2;
numbers.push(num3);
break;
case '-':
num2 = numbers.pop();
num1 = numbers.pop();
num3 = num1-num2;
numbers.push(num3);
break;
}
i++;
}
}while(i<input.length());
System.out.println("The result is: " + numbers.pop());
}
}
When I input a postfix expression it is outputting an incorrect number. For example when I input "5 3 2 * + 4 - 5 +" which evaluates to 12, it outputs 53.