Ronsen's Blog

Kalkulator atau sejenisnya

Friday, February 20, 2009

Lagi iseng membuat program sederhana menghitung Reverse Polish notation.

 package com.blogspot.i-temp;  
   
 import java.util.Stack;  
 import java.util.StringTokenizer;  
   
 public class Calculator {  
   
   public static final String EXPRESSION = "2 3 4 * +";  
   
   private Stack<Integer> stack = new Stack<Integer>();  
   
   public Calculator() {  
   }  
   
   private boolean isOperator(char ch) {  
     boolean operator = false;  
     switch (ch) {  
     case '+':  
     case '-':  
     case '*':  
     case '/':  
       operator = true;  
       break;  
     }  
     return operator;  
   }  
   
   private int compute(int op1, int op2, char operator) {  
     int result = 0;  
     switch (operator) {  
     case '+':  
       result = op1 + op2;  
       break;  
     case '-':  
       result = op1 - op2;  
       break;  
     case '*':  
       result = op1 * op2;  
       break;  
     case '/':  
       result = op1 / op2;  
       break;  
     }  
     return result;  
   }  
   
   public int parse(String expression) {  
     StringTokenizer tokens = new StringTokenizer(expression);  
     String token;  
     char operator;  
     int op1, op2;  
   
     while (tokens.hasMoreTokens()) {  
       token = tokens.nextToken();  
       operator = token.charAt(0);  
   
       if (isOperator(operator)) {  
         op2 = stack.pop();  
         op1 = stack.pop();  
         stack.push(compute(op1, op2, operator));  
       } else {  
         stack.push(new Integer(token));  
       }  
     }  
   
     return stack.pop();  
   }  
   
   public static void main(String[] args) {  
     Calculator calculator = new Calculator();  
     int result = calculator.parse(EXPRESSION);  
     System.out.println("Result: " + result);  
   }  
   
 }  

Ternyata yang sulit itu mengubah ekspresi matematika biasa ke RPN.