0

投稿されたコードは操作に対して機能しますが、演算子とオペランドの間にスペースがない場合は機能しません。

計算する4つの式が与えられました

  1. 10 2 8 * + 3 -

  2. 3 14+2*7/

  3. 4 2 + 3 15 1 - * +

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

(間隔は重要です)

式 2 は、現在の電卓を使用して計算しない式です

これが私のコードです

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

}
   }

ここにスタックトレースがあります

 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)
4

3 に答える 3

0

解析には StreamTokenizer を使用します。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);
  }
}
于 2013-11-16T01:25:54.797 に答える