Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Stack;
- import java.util.Scanner;
- public class TP2E08 {
- public static void main(String[] args) {
- TP2E08 exercise = new TP2E08();
- exercise.execute();
- }
- private void execute() {
- Scanner console = new Scanner(System.in);
- System.out.print("Ingrese una expresión interfija: ");
- String interFixExpression = console.nextLine();
- System.out.println("Expresión posfija: " + toPostFix(interFixExpression));
- console.close();
- }
- private String toPostFix(String interFixExpression) {
- String postFixExpression = "";
- Stack<Character> operators = new Stack<Character>();
- Character c;
- for (int i = 0; i < interFixExpression.length(); ++i) {
- c = interFixExpression.charAt(i);
- if ((c >= '0') && (c <= '9')) {
- postFixExpression += c;
- } else {
- while ((operators.size() > 0) && (precedence(operators.peek()) >= precedence(c))) {
- postFixExpression += operators.pop();
- }
- operators.push(c);
- }
- }
- while (operators.size() > 0) {
- postFixExpression += operators.pop();
- }
- return postFixExpression;
- }
- private int precedence(Character operator) {
- switch(operator) {
- case '+' :
- return 1;
- case '-' :
- return 1;
- case '*' :
- return 2;
- case '/' :
- return 2;
- default :
- return 3;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement