Postfix calc sólo funciona con un espaciamiento adecuado(es decir,3 14 2*7/ lanza una excepción)

StackOverflow https://stackoverflow.com//questions/20013474

Pregunta

El código publicado obras para las operaciones, pero no funciona si no hay espacio entre los operadores y operandos.

Me dieron 4 expresiones para calcular

  1. 10 2 8 * + 3 -

  2. 3 14+2*7/

  3. 4 2 + 3 15 1 - * +

  4. 1 2 + 3 % 6 - 2 3 + /

(espaciado es importante)

La expresión de los dos es el que no se calcula usando mi actual calculadora

Aquí está mi código

  import java.util.*;
  public class PostFix {

   public static void main(String []args){

    Stack<Integer> stack = new Stack<Integer>();
    System.out.println("Input your expression using postfix notation");
    Scanner input = new Scanner(System.in);
        String expr = input.nextLine();
        StringTokenizer tokenizer = new StringTokenizer(expr);

    while(tokenizer.hasMoreTokens()){
        String c = tokenizer.nextToken();
        if(c.startsWith("0")|| c.startsWith("1")||c.startsWith("2")||c.startsWith("3")||c.startsWith("4")||
            c.startsWith("5")||c.startsWith("6")||c.startsWith("7")||c.startsWith("8")||c.startsWith("9"))
            stack.push(Integer.parseInt(c));
        else if(c.equals("+")){
            int op1 = stack.pop();
            int op2= stack.pop();
            stack.push(op2+op1);
        }
        else if(c.equals("-")){
            int op1 = stack.pop();
            int op2= stack.pop();
            stack.push(op2-op1);
        }
        else if(c.equals("*")){
            int op1 = stack.pop();
            int op2= stack.pop();
            stack.push(op2*op1);
        }
        else if(c.equals("/")){
            int op1 = stack.pop();
            int op2= stack.pop();
            stack.push(op2/op1);
        }
        else if(c.equals("%")){
            int op1 = stack.pop();
            int op2= stack.pop();
            stack.push(op1%op2);
        }



    }
System.out.println(stack.pop());

}
   }

Aquí está el StackTrace

 Input your expression using postfix notation
 3 14+2*7/
 Exception in thread "main" java.lang.NumberFormatException: For input string:  "14+2*7/"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at PostFix.main(PostFix.java:18)
¿Fue útil?

Solución

Si usted realmente tiene que usar StringTokenizer, construir algo como esto:

StringTokenizer tokenizer = new StringTokenizer(expr, " +-*/%", true);

El segundo parámetro, dice que los espacios y todos los operadores son considerados como delimitadores, además de los espacios.El tercer parámetro, dice que los delimitadores son tratados como tokens, así que cuando se ve "+", "-", etc., volverá en la que, como una cadena.También regresará espacios, así que usted tiene que asegurarse de que cuando nextToken devuelve " ", usted lo ignora y no lo trata como un error.

Otros consejos

Alternativamente, si no puede usar StreamTokenizer, use la versión de 3 argumentos del constructor StringTokenizer:

StringTokenizer tokenizer = new StringTokenizer(expr, " +*-/", true);

Esto hará '', '+', '*', '-' y '/' delimitadores y también los informan como tokens.

Use un StreamTokenizer para analizar, consulte http://docs.oracle.com/javase/7/docs/api/java/io/streamtokenizer.html

StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(expr));
tokenizer.ordinaryChar('/');  // see comments

while(tokenizer.nextToken() != StreamTokenizer.TT_EOF){
  if (tonenizer.ttype == StreamTokenizer.TT_NUMBER) {
    stack.push(Integer.parseInt(tokenizer.sval));
  } else {
    int op1 = stack.pop();
    int op2 = stack.pop();
    switch (ttype) {
      case '+': op2 += op1; break;
      case '-': op2 -= op1; break;
      case '*': op2 *= op1; break;
      case '/': op2 /= op1; break;
    }
    stack.push(op2);
  }
}

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top