Domanda

Il codice pubblicato funziona per le operazioni ma non funzionerà se non c'è spazio tra gli operatori e gli operandi.

Mi sono state date 4 espressioni da calcolare

  1. 10 2 8 * + 3 -

  2. 3 14+2*7/

  3. 4 2 + 3 15 1 - * +

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

(la spaziatura è importante)

L'espressione due è quella che non verrà calcolata utilizzando la mia calcolatrice attuale

Ecco il mio codice

  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());

}
   }

Ecco lo 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)
È stato utile?

Soluzione

Se proprio devi usarlo StringTokenizer, costruiscilo in questo modo:

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

Il secondo parametro dice che gli spazi e tutti gli operatori sono considerati delimitatori, oltre agli spazi.Il terzo parametro dice che i delimitatori vengono trattati come token, quindi quando li vede "+", "-", ecc., lo restituirà come una stringa.Restituirà anche spazi, quindi devi assicurarti che quando nextToken ritorna " ", lo ignori e non lo tratti come un errore.

Altri suggerimenti

In alternativa, se non è possibile utilizzare StreamTokenizer, utilizzare la versione a 3 argoment del costruttore StringTokokerIzer:

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

Questo farà '', '+', '*', '-' e '/' delimitatori e li segnala anche come token.

Utilizza un StreamTokenizer per l'analisi, vedere 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);
  }
}
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top