infix notation to postfix in java

0

I hope they are very good.

I would like you to help me please with the following code:

import java.util.Scanner;
import java.util.Stack;

public class InfijaPrePost {

public static void main(String[] args) 
{
//se lee la notacion
    System.out.println("introduce notacion");
    Scanner sc = new Scanner(System.in);
    String notacion=sc.nextLine();

    //se llama al metodo postFija introduciendo como parametro la cadena ingresada por el usuario
    System.out.println(postFija(notacion));

}

/**
 * Metodo que retorna el array, compara cada elemento
 * segun la jerarquia de un operador en la notacion infija
 * recibida por el usuario.
 * 
 * @param infija Recibe la cadena dada por el usuario
 * @return la expresion de infija a postFija
 */
public static char[] postFija(String infija)
{
    /**
     * variable organizada de mayor a menor jerarquia
     */
    String jerarquia="^*/+- ";

    /**
     * variable para recorrer la posicion de la cadena infija
     */
    int pos_infija=0;
    /**
     * variable para recorrer la posicion de la variable jerarquia
     */
    int pos_jer=0;

    /**
     * creacion de un array para introducir los elementos de infija
     */
    char array[]=new char[infija.length()];

    /**
     * se introduce cada elemento de infija al array
     */
    for(int i=0;i<array.length;i++)
    {
        array[i]=infija.charAt(i);
    }

    /**
     * mientras la posicion de jerarquia no llegue a la posicion final de la variable jerarquia
     */
    while(pos_jer!=jerarquia.length()-1)
    {
        /**
         * Prueba de pantalla
         */
        /*for(int i=0;i<array.length;i++)
        {
            System.out.print(array[i]+" ");
        }*/
        //System.out.println("");

        /**
         * se valida si la posicion de la variable infija esta en el elemento final de dicha variable (infija)
         * en caso de ser verdadero, reestablecera la posicion y aumentara en 1 la posicion de la variable jerarquia
         */
        if(pos_infija==infija.length() )
        {
            pos_infija=0;
            pos_jer++;
        }

        /**
         * se compara el elemento de la notacion infija y la variable jerarquia
         * 
         */
        if(infija.charAt(pos_infija) == jerarquia.charAt(pos_jer) )
        {
            char aux = ' ';

            /**
             * se hace un "swap"
             */
            aux=array[pos_infija];

            array[pos_infija]=array[pos_infija+1];
            array[pos_infija+1]=aux;

            /*for(int i=0;i<array.length;i++)
            {
                System.out.print(array[i]+" ");
            }*/
        }
        /**
         * se incrementa en 1 la posicion de la notacion infija para volverla a comparar
         */
        pos_infija++;
    }


    return array;
}

}

What happens is that I want to convert an expression entered by keyboard and in this way convert it to postfia notation. My problem is that when I enter for example x + z * w the program prints: xy + w ** where its correct postfix notation would be: xzw * +

The parentheses () would not know how to "prioritize" them so that the program also reads notations with parentheses.

Thank you very much in advance, I hope you can help me.

    
asked by Yesith 09.04.2018 в 20:12
source

1 answer

0

I have this code in neatbens where I convert the infix to postfix notation, and it can be done with parentheses only that I have a problem where I enter by

ejemplo:
(A+B)*(C+D)
Me regresa:
AB+*CD+
Cuando deberia ser:
AB+CD+*

I do not know if it's a problem with my machine, but try it and if it fails you and you can correct the error, you tell me

Main Class:

public static void main(String[] args) {
        String Expresion, postfija="";  
        int i=0;
        Tipo_Pila Pila = new Tipo_Pila();
        Expresion = JOptionPane.showInputDialog("Teclear la expresión a validar:"); 
        char simbolo,elemento;
        while(i<Expresion.length()){
            simbolo=Expresion.charAt(i);
            if(!Pila.esOperador(simbolo))
                postfija+=simbolo;
            else{
                while(!Pila.pilaVacia() &&
                        Pila.Precedencia(Pila.Cima(), simbolo) ){
                    elemento=Pila.quitar();
                    postfija += elemento;
                }
                if (simbolo != ')') 
                    Pila.insertar(simbolo);  
                else           
                    Pila.quitar();
            }
            i++;
        }
        while(!Pila.pilaVacia()){
            elemento = Pila.quitar();
            postfija += elemento;
        }
        JOptionPane.showMessageDialog(null, postfija);
    } 

Secondary Class:

package postfija_parentesis;
public class Tipo_Pila {
    final static int MAX_ELEMENTOS = 100; 
    private int error;
    private int cima; 
    private char elemento[];
    public Tipo_Pila() {
        error = 0;
        cima = -1;
        elemento = new char [MAX_ELEMENTOS];  
    }
    public void insertar(char d) {  
        if (!pilaLlena()) elemento[++cima]= d; 
        else   
            error = 1;   
    } 
    public char quitar() { 
        if (!pilaVacia()) return elemento[cima--]; 
        else {
            error = 2; 
            return ' '; 
        }     
    }         
    public boolean pilaVacia() { 
        if (cima == -1)return true; 
        else 
            return false;   
    } 
    public boolean pilaLlena() { 
        if (cima == (MAX_ELEMENTOS - 1))return true; 
        else 
            return false;
    }     
    public int muestraError() {
        return error;
    } 
    public boolean Basico(char op){
        boolean r=false;
        if(op=='+') r=true;
        if(op=='-') r=true;
        if(op=='*') r=true;
        if(op=='/') r=true;
        if(op=='^') r=true;
        return r;
    }
    public boolean esOperador(char op){
        boolean r =Basico(op);
        switch (op){
            case '(':
            case ')': r=true;break;
        }
        return r;
    }
    public boolean Precedencia(char op, char op2){
        boolean r=false;
        if(op=='^' && Basico(op2)) r=true;
        if(op=='*' || op=='/' && Basico(op2) && op2!='^') r=true;
        if(op=='+' || op=='-' && op2=='+' || op2=='-') r=true;
        if(Basico(op) && op2==')')r=true;
        return r;
    }
    public char Cima(){
        return elemento [cima];
    }
}
    
answered by 06.10.2018 в 23:55