elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a Git (Primera Parte)


  Mostrar Temas
Páginas: [1]
1  Programación / Java / ayuda!! infijo a postfijo con 1 o mas digitos. en: 31 Mayo 2017, 20:22 pm
hola amigos, buen dia. alguien me podria ayudar a modificar un codigo de infijo a postfijo con pilas. son 2 cosas que necesito hacer:
1.-ejemplo  : Entrada : (100+5.75) + 100 -> salida : 100 5.75 + 100 +.
el problema es que solo acepta caracteres de 1 solo digito.

2.- la segunda modificacion es evaluar la raiz cuadra representado por el caracter '$' con un prioridad maxima. ejemplo Entrada : $(10*10) -30 ->salida 1 :  10 10 * $ 30 -  salida2 : -20 que es el resultado de la evalucacion.

de antemano les agradeceria su ayuda.

el codigo es el siguiente:

Código
  1. class InToPost // infix to postfix conversion
  2. {
  3.    private StackX theStack;
  4.    private String input;
  5.    private String output = "";
  6.    //--------------------------------------------------------------
  7.    public InToPost(String in) // constructor
  8.    {
  9.        input = in;
  10.        int stackSize = input.length();
  11.        theStack = new StackX(stackSize);
  12.    }
  13.    //--------------------------------------------------------------
  14.    public String doTrans() // lo traduce a postfijo
  15.    {
  16.        for(int j=0; j<input.length(); j++)
  17.        {
  18.            char ch = input.charAt(j);
  19.            theStack.displayStack("For "+ch+" "); // *diagnostico*
  20.            switch(ch)
  21.            {
  22.                case '+': // es + o -
  23.                case '-':
  24.                gotOper(ch, 1); // apila operadores
  25.                break; // (precedence 1)
  26.                case '*': // it's * or /
  27.                case '/':
  28.                gotOper(ch, 2); // apila operadores
  29.                break; // (precedence 2)
  30.  
  31.                case '$':
  32.                gotOper(ch, 3); // apila operador raiz cuadrada
  33.                break; // (precedence 3)
  34.  
  35.                case '(': // parentesis izquierdo
  36.                theStack.push(ch); // apilarlo
  37.                break;
  38.                case ')': // parentesis derecho
  39.                gotParen(ch); // apila
  40.                break;
  41.                default: // debe ser un operando
  42.                    output = output + ch; // escribiendo ala salida
  43.                    break;
  44.            } // fin del switch
  45.        } // fin del for
  46.        while( !theStack.isEmpty() ) // apila los restantes operadoeres
  47.        {
  48.            theStack.displayStack("While "); // *diagnostico*
  49.            output = output + theStack.pop(); // escribe la salida
  50.        }
  51.        theStack.displayStack("End "); // *diagnostico*
  52.        return output; // retorna el postfijo
  53.    } // fin de doTrans()
  54.    //--------------------------------------------------------------
  55.    public void gotOper(char opThis, int prec1)
  56.    { // Obtuvo el operador de la entrada
  57.        while( !theStack.isEmpty() )
  58.        {
  59.            char opTop = theStack.pop();
  60.            if( opTop == '(' ) // if es un '('
  61.            {
  62.                theStack.push(opTop); // restaura '('
  63.                break;
  64.            }
  65.            else // es un operador
  66.            {
  67.                int prec2; // precedencia de nuevo operador
  68.                if(opTop=='+' || opTop=='-') //encuentra nuevo operador de precedencia
  69.                prec2 = 1;
  70.                else
  71.                prec2 = 2;
  72.                if(prec2 < prec1) // if precedencia de nuevo operador es menor
  73.                { // que precedencia del viejo operador
  74.                    theStack.push(opTop); // guarda el nuevo operador
  75.                    break;
  76.                }
  77.                else // precedencia de nuevo operador no es menor
  78.                    output = output + opTop; // que prec del viejo operador
  79.            } // fin del else (es un operador)
  80.        } // fin while
  81.        theStack.push(opThis); // apila nuevo operador
  82.    } // fin gotOp()
  83.    //--------------------------------------------------------------
  84.    public void gotParen(char ch)
  85.    { // obtuvo parentesis derecho de la entrada
  86.        while( !theStack.isEmpty() )
  87.        {
  88.            char chx = theStack.pop();
  89.            if( chx == '(' ) // si es extraido '('
  90.            break; // esta listo
  91.            else // si es extraido el operador
  92.            output = output + chx; // output it
  93.        } // fin while
  94.    } // fin popOps()
  95.    //--------------------------------------------------------------
  96. } // fin de la clase InToPost
  97.  

clase evaluacion postfija
Código
  1. class ParsePost
  2. {
  3.    private StackX theStack;
  4.    private String input;
  5.    //--------------------------------------------------------------
  6.    public ParsePost(String s)
  7.    { input = s; }
  8.    //--------------------------------------------------------------
  9.    public int doParse()
  10.    {
  11.        theStack = new StackX(20); // crea una nueva pila
  12.        char ch;
  13.        int j;
  14.        int num1, num2, interAns;
  15.        for(j=0; j<input.length(); j++) // for para cada caracter (char),
  16.        {
  17.            ch = input.charAt(j); // lee la entrada
  18.            theStack.displayStack(""+ch+" "); // *diagnostico*
  19.            if(ch >= '0' && ch <= '9') // if es un numero
  20.            theStack.push((char) (ch-'0')); // lo  apila
  21.            else // es operador
  22.            {
  23.                num2 = theStack.pop(); // extrae operandos
  24.                num1 = theStack.pop();
  25.                switch(ch) // hace la evaluacion aritmetica
  26.                {
  27.                    case '+':
  28.                    interAns = num1 + num2;
  29.                    break;
  30.                    case '-':
  31.                    interAns = num1 - num2;
  32.                    break;
  33.                    case '*':
  34.                    interAns = num1 * num2;
  35.                    break;
  36.                    case '/':
  37.                    interAns = num1 / num2;
  38.                    break;
  39.                    case '$':
  40.  
  41.                    default:
  42.                        interAns = 0;
  43.                } // end switch
  44.                theStack.push((char) interAns); // apila el resultado
  45.            } // fin del  else
  46.        } // fin del for
  47.        interAns = theStack.pop(); // devuelve respuesta
  48.        return interAns;
  49.    } // fin doParse()
  50. } // fin de la clase ParsePost
  51.  

este es el codigo de la clase pila

Código
  1. class StackX
  2. {
  3.    private int maxSize;
  4.    private char[] stackArray;
  5.    private int top;
  6.    //--------------------------------------------------------------
  7.    public StackX(int s) // constructor
  8.    {
  9.        maxSize = s;
  10.        stackArray = new char[maxSize];
  11.        top = -1;
  12.    }
  13.    //--------------------------------------------------------------
  14.    public void push(char j) // pone un elemento en el tope de la pila
  15.    { stackArray[++top] = j; }
  16.    //--------------------------------------------------------------
  17.    public char pop() // toma un elemento del tope de la pila
  18.    { return stackArray[top--]; }
  19.    //--------------------------------------------------------------
  20.    public char peek() // obtiene el tope de la pila
  21.    { return stackArray[top]; }
  22.    //--------------------------------------------------------------
  23.    public boolean isEmpty() // verdadero si la pila westa vacia
  24.    { return (top == -1); }
  25.    //-------------------------------------------------------------
  26.    public int size() // regresa el tamano
  27.    { return top+1; }
  28.    //--------------------------------------------------------------
  29.    public char peekN(int n) // regresa el elemento al indice n
  30.    { return stackArray[n]; }
  31.    //--------------------------------------------------------------
  32.    public void displayStack(String s)
  33.    {
  34.        System.out.print(s);
  35.        System.out.print("Stack (bottom-->tope): ");
  36.        for(int j=0; j<size(); j++)
  37.        {
  38.            System.out.print( peekN(j) );
  39.            System.out.print(' ');
  40.        }
  41.        System.out.println("");
  42.    }
  43.    //--------------------------------------------------------------
  44. } // fin de la clase StackX
  45.  

y por ultimo la clase principal la cual testea el programa.

Código
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4.  
  5. class InfixApp {
  6.    public static void main(String[] args) throws IOException {
  7.        String input, output;
  8.        int eval;
  9.  
  10.        while(true) {
  11.            System.out.print("introduce el infijo: ");
  12.            System.out.flush();
  13.            input = getString(); // lee un string de kbd
  14.            if( input.equals("") ) // sale del programa si es [Enter]
  15.                break;
  16.            // crea la traduccion
  17.            InToPost theTrans = new InToPost(input);
  18.            output = theTrans.doTrans(); // hace la traduccion
  19.            System.out.println("Postfix is " + output + '\n');
  20.            ParsePost aParser = new ParsePost(output);
  21.            eval = aParser.doParse(); // hace la evaluacion
  22.            System.out.println("Evaluates to " + eval);
  23.        } // fin del while
  24.    } // fin del  main()
  25.    //--------------------------------------------------------------
  26.    public static String getString() throws IOException
  27.    {
  28.        InputStreamReader isr = new InputStreamReader(System.in);
  29.        BufferedReader br = new BufferedReader(isr);
  30.        String s = br.readLine();
  31.        return s;
  32.    }
  33.    //--------------------------------------------------------------
  34. } // fin de la clase InfixApp
  35.  






Páginas: [1]
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines