package Question_8;
import java.util.*;
import java.util.regex.*;
import java.lang.*;
public class Count {
String[] operater = new String[20];
String[] number = new String[20];
public double countExpression(String str) {
Stack countStack1 = new Stack();
Stack countStack2 = new Stack();
double result = 0;
number = str.split("///|//*|//+|//-");
operater = str.split("//d+");
for (int i = 0; i < number.length; i++) {
countStack1.push(number[i]);
if (i != number.length - 1) {
countStack1.push(operater[i + 1]);
}
}
while (!countStack1.isEmpty()) {
countStack2.push(countStack1.pop());
}
String op;
while (!countStack2.isEmpty()) {
result = 0;
op = countStack2.pop().toString();
if (op.equals("*")) {
result = Double.parseDouble(countStack1.pop().toString())
* Double.parseDouble(countStack2.pop().toString());
countStack1.push(result);
continue;
}
if (op.equals("/")) {
result = Double.parseDouble(countStack1.pop().toString())
/ Double.parseDouble(countStack2.pop().toString());
countStack1.push(result);
continue;
}
countStack1.push(op);
}
while (!countStack1.isEmpty()) {
countStack2.push(countStack1.pop());
}
while (!countStack2.isEmpty()) {
result = 0;
op = countStack2.pop().toString();
if (op.equals("+")) {
result = Double.parseDouble(countStack1.pop().toString())
+ Double.parseDouble(countStack2.pop().toString());
countStack1.push(result);
continue;
}
if (op.equals("-")) {
result = Double.parseDouble(countStack1.pop().toString())
- Double.parseDouble(countStack2.pop().toString());
countStack1.push(result);
continue;
}
countStack1.push(op);
}
return result;
// System.out.println(result);
}
/*public static void main(String[] args) {
int num1;
Input_ input = new Input_();
String a = input.InputString_();
Count ct1 = new Count();
num1 = ct1.countExpression(a);
System.out.println(num1);
}
*/
}
stack2
最新推荐文章于 2024-03-04 11:59:48 发布