Prevod aritmetického výrazu z infix do postfix (poľskej notácie)

Created: 2008-06-19 - 17:06


import java.util.*;

public class InfixToPostfix {
	public static String convertToPostfix(String entry) {
		String result = "";
		Stack<String> vysledok = new Stack<String>();
		Stack<String> operatory = new Stack<String>();
		StringTokenizer tok = new StringTokenizer(entry, "+-*/()", true);

		while (tok.hasMoreTokens()) {
			String dalsi = tok.nextToken();
			try {
				Integer.parseInt(dalsi);
				vysledok.add(dalsi);
			} catch (Exception e) {
				if (operatory.isEmpty()) {
					operatory.push(dalsi);
				} else {
					if (!operatory.isEmpty() && !dalsi.equals("(")
							&& !dalsi.equals(")")) {
						while (!operatory.empty() && !(operatory.peek()).equals("(") && 
								prec(dalsi)<=prec(operatory.peek())){
								vysledok.push(operatory.pop());
						}
							operatory.push(dalsi);
					} else if (dalsi.equals("("))
						operatory.push(dalsi);
					else if (dalsi.equals(")")) {
						do {
							vysledok.add(operatory.pop());
							if (operatory.peek().equals("("))
								break;
						} while (0 == 0);
						operatory.pop();
					}
				}
			}
		}
		while (!operatory.isEmpty())
			vysledok.add(operatory.pop());

		result = vysledok.toString();
		return result;
	}
	
	private static int prec(String o1){
		if(o1.equals("+"))
			return 0;
		if(o1.equals("-"))
			return 0;
		if(o1.equals("*"))
			return 1;
		if(o1.equals("/"))
			return 0;
		else return 0;
	}
}