使用步骤
- 1.将一个字符串算式先转换成后缀表达式
- 2.把后缀表达式转换成结果
相关的代码如下
import java.util.Scanner;
import java.util.Stack;
public class Task3_22 {
public static void Suffix(String str){
Stack<Character> s = new Stack<>();
int position = 0;
MyArrayList<String> my = new MyArrayList<>();
for(int i=0; i<str.length(); i++){
char c = str.charAt(i);
switch(c){
case '+':
case '-':
my.add(str.substring(position, i));
position = i+1;
while(!s.empty() && s.peek() != '('){
my.add(s.pop()+"");
}
s.push(c);
break;
case '*':
case '/':
my.add(str.substring(position, i));
position = i+1;
while(!s.empty() && s.peek() != '+' && s.peek() != '-' && s.peek() != '('){
my.add(s.pop()+"");
}
s.push(c);
break;
case '(':
my.add(str.substring(position, i));
position = i+1;
s.push(c);
break;
case ')':
my.add(str.substring(position, i));
position = i+1;
while(!s.empty() && s.peek() != '('){
my.add(s.pop()+"");
}
s.pop();
break;
case '^':
my.add(str.substring(position, i));
position = i+1;
while(!s.empty() && s.peek() == '^' || s.peek() == '('){
my.add(s.pop()+"");
}
s.push(c);
break;
case '=':
my.add(str.substring(position, i));
while(!s.empty()){
my.add(s.pop()+"");
}
break;
}
}
for(int i=0; i<my.size(); i++){
System.out.print(my.get(i));
}
System.out.println();
evalPostfix(my);
}
public static void evalPostfix(MyArrayList<String> my){
Stack<Double> s = new Stack<Double>();
Double a, b, result = 0.0;
boolean isNumber;
for(int i=0; i<my.size(); i++){
try{
isNumber = true;
result = Double.parseDouble(my.get(i));
}catch(Exception e){
isNumber = false;
}
if(isNumber)
s.push(result);
else{
switch(my.get(i)){
case "+":
a = s.pop(); b = s.pop();
s.push(b+a); break;
case "-":
a = s.pop(); b = s.pop();
s.push(b-a); break;
case "*":
a = s.pop(); b = s.pop();
s.push(b*a); break;
case "/":
a = s.pop(); b = s.pop();
s.push(b/a); break;
case "^":
a = s.pop(); b = s.pop();
s.push(Math.exp(a*Math.log(b)));
break;
}
}
}
System.out.println(s.peek());
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.next();
Suffix(str);
}
}