All pastes #229817 Raw Edit

Miscellany

public java v1 · immutable
#229817 ·published 2006-10-30 23:19 UTC
rendered paste body
import java.util.Scanner;import java.util.Stack;import java.util.LinkedList;public class PrefixSolver {  public static void main(String[] args) {    Scanner in = new Scanner(System.in);    System.out.print("Enter a prefix notation: ");    System.out.println("Result: "+eval(in.next()));  }    public static int eval(String prefix) {    LinkedList<Integer> operand = new LinkedList<Integer>();    Stack<Character> operator = new Stack<Character>();    char[] chr = new char[prefix.length()];    chr = prefix.toCharArray();    int result = 0;    for (int i=0; i<chr.length; i++) {      if (chr[i] >= '0' && chr[i] <= '9') {        operand.add(((int)chr[i]-'0'));      }      if (chr[i]=='+'||chr[i]=='-'||chr[i]=='*'||chr[i]=='/') {        operator.push(chr[i]);      }      if (operand.size() >= 2 && !operator.empty()) {        int op1, op2; char op;        op = operator.pop();        op1 = operand.poll();        op2 = operand.poll();        switch (op) {          case '+': operand.add(op1+op2); break;          case '-': operand.add(op1-op2); break;          case '*': operand.add(op1*op2); break;          case '/': operand.add(op1/op2); break;        }        result = operand.peek();      }    }/*    System.out.print("Operands: ");    while (operand.size() > 0) {      System.out.print(operand.poll()+" ");    }    System.out.print("\nOperators: ");    while (!operator.empty()) {      System.out.print(operator.pop()+" ");    }*/    return result;  }}