只能寫出個位數,實力還不夠阿(嘆~)
import java.io.*;
class date{
public static int priority(char op) {
switch(op) {
case '+': case '-':
return 1;
case '*': case '/':
return 2;
case '^':
return 3;
default:
return 0;
}
}
public static char[] toPosfix(char[] infix) {
char[] stack = new char[infix.length];
char[] postfix = new char[infix.length];
char op;
StringBuffer buffer = new StringBuffer();
int top = 0;
for(int i = 0; i op = infix[i];
switch(op) {
case '(':
if(top top++;
stack[top] = op;
}
break;
case '+': case '-': case '*': case '/':
while(priority(stack[top]) >= priority(op) ) {
buffer.append(stack[top]);
top--;
}
if(top top++;
stack[top] = op;
}
break;
case ')':
while(stack[top] != '(') {
buffer.append(stack[top]);
top--;
}
top--;
break;
default:
buffer.append(op);
break;
}
}
while(top > 0) {
buffer.append(stack[top]);
top--;
}
return buffer.toString().toCharArray();
}
public static double cal(double p1, char op, double p2) {
switch(op) {
case '+':
return p2 + p1;
case '-':
return p2 - p1;
case '*':
return p2 * p1;
case '/':
return p2 / p1;
}
return 0.0;
}
public static double eval(char[] postfix) {
double[] stack = new double[postfix.length];
char token;
int top = 0;
for(int i = 0; i token = postfix[i];
switch(token) {
case '+':
case '-':
case '*':
case '/':
stack[top-1] = cal(stack[top], token, stack[top-1]);
top--;
break;
default:
if(top char temp = postfix[i];
top++;
stack[top] = Double.parseDouble(String.valueOf(temp));
}
break;
}
}
return stack[top];
}
}
public class j1028{
public static void main(String[] args)
throws IOException {
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("請輸入運算式:");
String infix = br.readLine();
System.out.println(date.toPosfix(infix.toCharArray()));
System.out.println(date.eval(date.toPosfix(infix.toCharArray())));
}
}
- Jan 23 Tue 2007 00:29
中置運算式轉後置並運算
全站熱搜
留言列表
發表留言