需要用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
// 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
解决方案 »
- 求java高手!!!!!!!!
- Java 如何指定 TextField 在 JPanel中的位置
- rtp协议在这里如何应用?做过的都进来看看
- 怎么样返回一个接口类型
- JAVA里面如何判断数据数据类型
- 关于转码的2个奇怪问题,高手看一下!谢谢
- 请高手指教--怎么用javac编译互相import的包?
- 有什么方法以字符串来分割一文本文件??
- java.io 莱鸟问题:程序运行时用到的文件应该放在哪个目录下?在线等待。。。
- 如何把applet窗口里的Java Applet Window去掉?
- 求助:java中哪个类能获得当前计算机名
- 求huffman压缩解压缩的java代码(可以压缩任何文件,不仅是text文件)。谢谢
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
但是要可以输入和输出的,不要再程序里面编写进去的那种!谢谢啦~
似乎这个例子只是支持单数字啊。
网上找了另外一个。 当给自己补习了。
http://www.idcnews.net/html/edu/java/20071109/104562.html //else if (stack.empty() ¦ ¦ch == '(')// 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
}
}
http://www.cs.utsa.edu/~wagner/CS1723/fall01/eval/eval.html
// 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;
}
}
你是想计算表达式的值吗??
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();
}
}
}