需要用java编写这个程序,要求是 a + b * c  convert to a b c * +我找了个程序但是上面缺省部分class,我刚开始学java,实在不知道该怎么样编写那个GetNext class,也不知道到底该加在哪里,所以希望大家帮我看看应该怎么做,谢谢啦~
// Eval: evaluate RPN string
//  single digits, treated as doubles, and operators
import java.util.*;
public class Eval {    Stack stack; // java library stack of objects
   public Eval() {
      stack = new Stack();
   }   // evaluateRPN: evaluate the RPN as doubles
   public double evaluateRPN(String s) {
      double op1 = 0.0, op2 = 0.0, res = 0.0;
      for (int i = 0; i < s.length(); i++) {
         char ch = s.charAt(i);
         if (Character.isDigit(ch) ) { // push Double
            stack.push(new Double( (double)(ch - '0')));
         }
         else { // char is an operator
            if (stack.empty())
               error(1);
            else
               op2 = 
                 ((Double)(stack.pop())).doubleValue();
            if (stack.empty())
               error(2);
            else
               op1 = 
                 ((Double)(stack.pop())).doubleValue();
            res = evaluate(ch, op1, op2);
            stack.push(new Double(res));
         }
      }
      if (stack.empty())
         error(4);
      else
         res = ((Double)(stack.pop())).doubleValue();
      if (!stack.empty())
         error(5);
      return res;
   }   // evaluate: actually perform operator
   private double evaluate(char ch, double op1,
         double op2) {
      switch(ch) {
         case '+': return op1 + op2;
         case '-': return op1 - op2;
         case '*': return op1 * op2;
         case '/': return op1 / op2;
         case '^': return Math.pow(op1, op2);
         default: error(3); return 0;
      }
   }   // error: in case of an error
   private void error(int num) {
      System.out.println("Error number: " + num);
      System.exit(0);
   }
}
// Trans: translate input arith expr to RPN string
// Rules for each input char
//  (go on to next input char unless otherwise stated)
// Fetch next char, call it ch
// 1. if ch is an operand, move it to output.
// From now on ch is an operator or '(' or ')'.
// 2. if stack is empty, add ch to stack.
// 3. if ch is '(', add ch to stack.
// From now on, stack not empty. Use top for top char.
// 4. if ch is ')', remove chars from stack and output
//    down to '(' on stack, which is thrown away.
// 5. if top is '(', add ch to stack.
// From now on, both ch and top are regular operators.
// 6. if prec(ch) > prec(top), add ch to stack.
// 7. if prec(ch) < prec(top), move top to output, and
//    DO NOT MOVE ON TO NEXT INPUT CHAR.
// 8. if prec(ch) == prec(top) and left-to-right assoc,
//    move top to output, and DO NOT MOVE TO NEXT CHAR.
// 9. if prec(ch) == prec(top) and right-to-left assoc,
//    add top to stack.
// 10. at end, move everything on stack to output.

import java.util.*;
public class Trans {    Stack stack; // java library stack of objects
   public Trans() {
      stack = new Stack();
   }   // translate: an arith expr to RPN
   public String translate(String s) {
      double op1 = 0.0, op2 = 0.0, res = 0.0;
      String outStr = ""; // output string
      char ch, top;
      int i = 0; // index in input string
      while (i < s.length()) {
         boolean moveOn = true;
         ch = s.charAt(i); // before Rule 1
         if (Character.isDigit(ch) ) // Rule 1
            outStr += ch;
         else if (stack.empty()||ch == '(')// Rules 2, 3
            stack.push(new Character(ch));
         else { // stack is not empty
            top =   // before Rule 4 
               ((Character)(stack.peek())).charValue();
            if (ch == ')') // Rule 4
               while (true) {
                  if ((top=((Character)(stack.pop())).
                        charValue()) == '(')
                     break; // normal termination
                  outStr += top;
                  if (stack.empty()) error(1);
               }
            else if (top == '(') // Rule 5
               stack.push(new Character(ch));
            else if (prec(ch) > prec(top) ||
                   (prec(ch) == prec(top) &&
                    assoc(ch) == 'r') ) // Rules 6, 9
               stack.push(new Character(ch));
            else if (prec(ch) < prec(top) ||
                   (prec(ch) == prec(top) &&
                    assoc(ch) == 'l') ) { // Rules 7, 8
               outStr += top;
               stack.pop();
               moveOn = false;
            }
         }
         if (moveOn) i++;
      } // while
      while (!stack.empty()) // Rule 10
        outStr +=((Character)(stack.pop())).charValue();
      return outStr;
   }   // prec: return int precedence of operators
   private int prec(char ch) {
      switch (ch) {
         case '+': case '-': return 1;
         case '*': case '/': return 2;
         case '^': return 3;
         default: return -1;
      }
   }   // assoc: return 'l' for l-to-r, and 'r' for r-to-l
   private char assoc(char ch) {
      switch (ch) {
         case '+':case '-':case '*':case '/':return 'l';
         case '^': return 'r';
         default: return '?';
      }
   }   // error: in case of an error
   private void error(int num) {
      System.out.println("Error number: " + num);
      System.exit(0);
   }   public static void main(String[] args) {
      GetNext getNext = new GetNext(); // input class
      Trans trans = new Trans(); // new translater
      Eval eval = new Eval(); // new evaluator
      while (true) { // read and translate indefinitely
         String s = getNext.getNextString(); // input 
         System.out.println("Input: " + s);
         String resStr = trans.translate(s); // RPN
         System.out.println("RPN string: " + resStr);
         double res = eval.evaluateRPN(resStr);
         System.out.println("Value: " + res); // print
      }
   }
}最后要达到的要求就是2*3+4
Input: 2*3+4
RPN string: 23*4+
Value: 10.02^3^4
Input: 2^3^4
RPN string: 234^^
Value: 2.4178516392292583E242*(3+4)
Input: 2*(3+4)
RPN string: 234+*
Value: 14.0

解决方案 »

  1.   

    那请问一下,又没有什么简单点的方法也能达到这题上面的要求阿?就是,
    2*3+4 
    Input: 2*3+4 
    RPN string: 23*4+ 
    Value: 10.0 2^3^4 
    Input: 2^3^4 
    RPN string: 234^^ 
    Value: 2.4178516392292583E24 2*(3+4) 
    Input: 2*(3+4) 
    RPN string: 234+* 
    Value: 14.0 
    但是要可以输入和输出的,不要再程序里面编写进去的那种!谢谢啦~
      

  2.   

    逆波兰表达式,又称后序, 数据结构没学好,看得头晕啊。 见红色部分
    似乎这个例子只是支持单数字啊。
    网上找了另外一个。 当给自己补习了。
    http://www.idcnews.net/html/edu/java/20071109/104562.html         //else if (stack.empty() ¦ &brvbarch == '(')// Rules 2, 3
             else if (stack.empty() || ch == '(')// Rules 2, 3   static class GetNext {
           private java.io.BufferedReader br = null;
           public GetNext() {
               br = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
           }
           public String getNextString() throws IOException {
               System.out.print("Please input the string:");
               return br.readLine();
           }
           
           
       }
       public static void main(String[] args) throws Exception {
          GetNext getNext = new GetNext(); // input class
          Trans trans = new Trans(); // new translater
          Eval eval = new Eval(); // new evaluator
          while (true) { // read and translate indefinitely
             String s = getNext.getNextString(); // input 
             System.out.println("Input: " + s);
             String resStr = trans.translate(s); // RPN
             System.out.println("RPN string: " + resStr);
             double res = eval.evaluateRPN(resStr);
             System.out.println("Value: " + res); // print
          }
       }
       
      

  3.   

    你需要的类在这:
    http://www.cs.utsa.edu/~wagner/CS1723/fall01/eval/eval.html
      

  4.   

    我自己试了一下发现那个程序有点小bug,修改后的GetNext类如下:
    // GetNext: fetch next char or unsigned integer
    import java.io.*;
    public class GetNext { 
       private Reader in; // internal file name for input stream
      
       // GetNext: constructor  
       public GetNext () { 
          in = new InputStreamReader(System.in);
       }   // getNextChar: fetches next char
       private char getNextChar() {
          char ch = ' '; // = ' ' to keep compiler happy
          try {
             ch = (char)in.read();
          } catch (IOException e) {
             System.out.println("Exception reading character");
          }
          return ch;
       }   // getNextString: fetch String
       public String getNextString() {
          String s ;
          char ch = getNextChar();
          while (ch == ' ' || ch == '\n' || ch=='\r')//我在这里添加了“||ch!='\r'”
             ch = getNextChar();
          s = "" + ch;
          while ((ch = getNextChar()) != ' ' && ch != '\n' && ch != '\r') //我在这里添加了“&&ch!='\r'”
             s += ch;
          return s;
       }
      

  5.   

    没学过数据结构,看着一头雾水
    你是想计算表达式的值吗??
    jdk1.6有现成的类可以用的啊:import java.io.*;
    import java.util.*;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptEngine;public class a {
        public static void main(String[] args) {
            try {
                Scanner sc = new Scanner(System.in);
                String exp = sc.nextLine();
                ScriptEngineManager factory = new ScriptEngineManager();
                ScriptEngine eng = factory.getEngineByName("javascript");
                System.out.println(eng.eval("eval(" + exp + ")"));
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }