2008-04-04

Java Postfix Calculator

Day 404.

Goal: Java application to split string into arguments with postfix arithmetic operations and calculate the result.

Input:

  • "2 3+ 4*"
Calculating:
  1. 0 + 2 = 2
  2. 2 + 3 = 5
  3. 5 * 4 = 20
Result:
  • 20
Don't ask. It is just another module for the World Saving API.

import java.util.Stack;

public class Calculate {

public static void main(String argv[]) {
try {
int i;
String argument;
Stack<String> stack = new Stack<String>();

// Parses input string
// Uses everything except 0..9 and */+- as delimiters
String arguments[] = argv[0].split("[^0-9*/+-]{1,}");

// Fills argument stack
// Java Stack is LIFO structure and is to be filled from last element
for (i = arguments.length - 1; i >= 0; i--) {
argument = arguments[i].trim();
if (!argument.equals("")) {
stack.push(argument);
}
}

// Calculates result
long result = 0;
while (!stack.empty()) {
argument = stack.pop().trim();

// Skips empty strings -- nothing to do with them
if (argument.equals("")) {
continue;
}

if (argument.endsWith("*")) {
// If first element is N*, this result will remain 0
result *= Double.valueOf(argument.replace("*", ""));
} else if (argument.endsWith("/")) {
// Exception thrown by division by 0 is handled by catch() below
result /= Double.valueOf(argument.replace("/", ""));
} else if (argument.endsWith("+")) {
result += Double.valueOf(argument.replace("+", ""));
} else if (argument.endsWith("-")) {
result -= Double.valueOf(argument.replace("-", ""));
} else {
// Default operation is adding argument
result += Double.valueOf(argument);
}
}

// Output result
System.out.println(result);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}


Questions? Problems?

No comments: