문제

코드시 작품에 대한 운영지 않을 경우 작동이 간격을 사업자 및 피연산자를 사용합니다.

내가 주어진 4 개 표현하는 계산

  1. 10 2 8 * + 3 -

  2. 3 14+2*7/

  3. 4 2 + 3 15 1 - * +

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

(간격은 중요한)

식 두 가지는 하나이지 않은 컴퓨팅을 사용하여 현재의 내 계산기

여기에 내 코드

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

}
   }

여기에는 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)
도움이 되었습니까?

해결책

당신이 정말로 필요하다면 사용 StringTokenizer,그것을 구성하는 다음과 같다:

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

두 번째 매개 변수는 공간과 모든 사업자는 고려 구분 기호 이외에,공간이 있습니다.세 번째 매개 변수는 구분 기호는 치료 토큰으로,그래서 그 때 그것을 보고 "+", "-",etc., 그것은 반환되는 문자열로.그것은 또한 반환을 공간,그래서 당신이 있는지 확인해야 하는 경우 nextToken" ", 에,당신은 그것을 무시하고 하지 않으로 처리하여 오류가 있습니다.

다른 팁

또는 StreamTokenizer를 사용할 수없는 경우 StringTokenizer 생성자의 3 인수 버전을 사용하십시오.

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

이것은 '', '+', '*', '-'및 '/'구분 기호를 만들고 토큰으로보고합니다.

구문 분석을 위해 StreamTokenizer를 사용하십시오. "nofollow"> 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);
  }
}
.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top