2012-06-25 64 views
6

He creado una calculadora de pila para mi clase de Java para resolver ecuaciones tales comoPostfix calculadora pila

2 + (2 * (10 – 4)/((4 * 2/(3 + 4)) + 2) – 9) 
2 + { 2 * (10 – 4)/[ { 4 * 2/(3 + 4) } + 2 ] – 9 } 

Estamos suponer para implementar { } [ ] en nuestro código. Lo hice solo entre paréntesis. Funciona al 100% con solo (). Cuando intento agregar { } [ ], sale bananas.

Esto es lo que tengo hasta ahora:

package stackscalc; 

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


class Arithmetic { 
    int length; 
    Stack stk; 
    String exp, postfix; 

    Arithmetic(String s) { 
     stk = new Stack(); 
     exp = s; 
     postfix = ""; 
     length = exp.length(); 

    } 
    boolean isBalance() { 
     boolean fail = false; 
     int index = 0; 

     try { 
      while (index < length) { 
       char ch = exp.charAt(index); 

       switch(ch) { 
       case ')': 
        stk.pop(); 
        break; 

       case '(': 
        stk.push(new Character(ch)); 
        break; 

       default: 
        break; 
       } 
       index++; 
      } 
     } catch (EmptyStackException e) { 
      fail = true; 
     } 
     return stk.empty() && !fail; 
    } 
    void postfixExpression() { 
     String token = ""; 
     Scanner scan = new Scanner(exp); 
     stk.clear(); 

     while(scan.hasNext()) { 
      token = scan.next(); 
      char current = token.charAt(0); 

      if (isNumber(token)) { 
       postfix = postfix + token + " "; 
      } else if(isParentheses(current)) { 
       if (current == '(') { 
        stk.push(current); 
       } else { 
        Character ch = (Character) stk.peek(); 
        char nextToken = ch.charValue(); 

        while(nextToken != '(') { 
         postfix = postfix + stk.pop() + " "; 

         ch = (Character) stk.peek(); 

         nextToken = ch.charValue(); 
        } 
        stk.pop(); 
       } 
      } else { 
       if (stk.empty()) { 
        stk.push(current); 
       } else { 
        Character ch = (Character) stk.peek(); 
        char top = ch.charValue(); 

        if (hasHigherPrecedence(top, current)) { 
         stk.push(current); 
        } else { 
         ch = (Character) stk.pop(); 

         top = ch.charValue(); 

         stk.push(current); 

         stk.push(top); 
        } 
       } 
      } 
     } 
     try { 
      Character ch = (Character) stk.peek(); 
      char nextToken = ch.charValue(); 

      while (isOperator(nextToken)) { 
       postfix = postfix + stk.pop() + " "; 
       ch = (Character) stk.peek(); 
       nextToken = ch.charValue(); 
      } 
     } catch (EmptyStackException e) {} 
    } 
    boolean isNumber(String s) { 
     try { 
      int Num = Integer.parseInt(s); 
     } catch(NumberFormatException e) { 
      return false; 
     } 
     return true; 
    } 
    void evaluateRPN() { 
     Scanner scan = new Scanner(postfix); 
     String token = ""; 
     stk.clear(); 

     while(scan.hasNext()) { 
      try { 
       token = scan.next(); 
       if (isNumber(token)) { 
        stk.push(token); 
       } else { 
        char current = token.charAt(0); 
        double t1 = Double.parseDouble(stk.pop().toString()); 
        double t2 = Double.parseDouble(stk.pop().toString()); 
        double t3 = 0; 

        switch (current) { 
        case '+': { 
         t3 = t2 + t1; 
         stk.push(t3); 
         break; 
        } 
        case '-': { 
         t3 = t2 - t1; 
         stk.push(t3); 
         break; 
        } 
        case '*': { 
         t3 = t2 * t1; 
         stk.push(t3); 
         break; 
        } 
        case '/': { 
         t3 = t2/t1; 
         stk.push(t3); 
         break; 
        } 
        default: { 
         System.out.println("Reverse Polish Notation was unable to be preformed."); 
        } 
       } 
      } 

     } catch (EmptyStackException e) {} 
    } 
} 
String getResult() { 
    return stk.toString(); 
} 

int stackSize() { 
    return stk.size(); 
} 

boolean isParentheses(char current) { 
    if ((current == '(') || (current == ')')) { 
     return true; 
    } else { 
     return false; 
    } 
} 

boolean isOperator(char ch) { 
    if ((ch == '-')) { 
     return true; 
    } else if ((ch == '+')) { 
     return true; 
    } 
    else if ((ch == '*')) { 
     return true; 
    } 
    else if((ch == '/')) { 
     return true; 
    } else { 

    } 
    return false; 
} 

boolean hasHigherPrecedence(char top, char current) { 
    boolean HigherPre = false; 

    switch (current) { 
    case '*': 
     HigherPre = true; 
    break; 

    case '/': 
     HigherPre = true; 
    break; 

    case '+': 

     if ((top == '*') || (top == '/') || (top == '-')) { 
      HigherPre = false; 
     } else { 
      HigherPre = true; 
     } 

     break; 

    case '-': 
     if ((top == '*') || (top == '/') || (top == '-')) { 
      HigherPre = false; 
     } else { 
      HigherPre = true; 
     } 
     break; 

    default: 
     System.out.println("Higher Precedence Unsuccessful was unable to be preformed."); 
     break; 
    } 

    return HigherPre; 


    } 

    String getPostfix() { 
     return postfix; 
    } 
} 
+0

Se supone que debes agregar '{} []' para hacer exactamente eso? – EJP

Respuesta

1

Lo que yo estoy asumiendo es que(), {}, y [] todos tienen el mismo peso en términos de orden de las operaciones, y sólo tiene para modificar su código para permitir que los tres se intercambien.

Si ese es el caso, simplemente usaría la clase de emparejador con una simple comprobación de expresiones regulares para ver si el carácter actual que está viendo es un paréntesis, una llave o un paréntesis.

//convert char to string 
    String temp += currentChar; 
    //this will check for (, [, and { (need escapes because of how regex works in java) 
    Pattern bracePattern = Pattern.compile("[\(\{\[]"); 
    Matcher matcher = numPatt.matcher(temp); 
    if(matcher.find()){ 
    //you know you have a grouping character 
    } 

Este código debe permitir encontrar todos los caracteres de agrupamiento de apertura (solo suplente (, {, y [para), y}] en la expresión regular para encontrar caracteres de cierre). Esto se puede usar en su método isParenthesis().

+2

También debería actualizar las líneas como 'if (current == '(')' y 'while (nextToken! = '(')'). Your 'isParenthesis()' también busca parientes cercanos, por lo que asegúrate de no intentar y copiar/pegar esta respuesta = P – Windle

+1

Buena llamada. Estaba un poco vago en el uso de la verificación de expresiones regulares. –

+2

No quieres procesar '(2 + 3}', ¿Vos si? – Arkadiy

Cuestiones relacionadas