?? calculatestring.java
字號:
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class CalculateString {
final int VARIABLE = 1;
final int NUMBER = 2;
public String variable;
public double value;
public String function;
public int number_of_arguments;
public void Variable( String variable, double value )
{
this.variable=variable;
this.value=value;
}
public void Function( String function, int number_of_arguments )
{
this.function=function;
this.number_of_arguments=number_of_arguments;
}
public BigDecimal calculateString(String str) //計算表達式
{
char[] strs = str.toCharArray(); //返回輸出數組的拷貝
Stack<String> stack = new Stack<String>();
for (int i = 0; i < strs.length; i++)
{
String stackStr = String.valueOf(strs[i]); //將strs中的字符轉換為字符串,并返回
stack.push(stackStr); //壓入棧中
if ( ")".equals(stack.top()) ) //如果是")"繼續尋找
{
String subStr = null;
while (!"(".equals(stack.top()))
{
stack.pop();
if (!"(".equals(stack.top()))
{
subStr = addEnd(subStr, stack.top());
}
}
String pushStr = CalculateReversePolishExpression(subStr);
stack.pop();
stack.push(pushStr);
}
}
String resultStr = null;
while (stack.count != 0)
{
resultStr = CalculateReversePolishExpression(stack.toString());
}
BigDecimal result = null;
if (resultStr != null)
{
result = new BigDecimal(resultStr);
} else
{
result = BigDecimal.ZERO; //讓result的值為0.標度為0;
}
return result.setScale(2, BigDecimal.ROUND_HALF_UP); //返回一個 BigDecimal,其標度為指定值
//向"最接近的"數字舍入,如果與兩個相鄰數字的距離相等,
//則為向上舍入的舍入模式。
}
public String[] matcher(String regex, String str) { //匹配器
Pattern pattern = Pattern.compile(regex); //將正則表達式編譯到模式中
Matcher matcher = pattern.matcher(str); //創建匹配給定輸入與此模式的匹配器
List<String> list = new ArrayList<String>();
while (matcher.find()) {
list.add(matcher.group());
}
String[] result = new String[list.size()];
return list.toArray(result);
}
public List<String> createReversePolishExpression(String subStr) { //構造逆波蘭表達式
String regex = "\\d+\\.{0,1}\\d*";
String[] numbers = matcher(regex, subStr);
String changeStr = subStr.replaceAll(regex, "0").replaceAll("\\-\\-0",
"-1").replaceAll("\\+\\-0", "+1").replaceAll("\\*\\-0", "*1") //用正則表達式來匹配
.replaceAll("\\/\\-0", "/1");
char[] chars = changeStr.toCharArray();
int index = 0;
List<String> list = new ArrayList<String>(); //指針列表
for (int i = 0; i < chars.length; i++) {
String str = String.valueOf(chars[i]);
if ("0".equals(str)) {
list.add(numbers[index++]);
} else if ("1".equals(str)) {
list.add("-" + numbers[index++]);
} else {
list.add(str);
}
}
List<String> suffix = new ArrayList<String>();
Stack<String> operator = new Stack<String>();
for (int i = 0; i < list.size(); i++) {
if (!isOperatorType(list.get(i))) {
suffix.add(list.get(i));
} else {
if (operator.count == 0) {
operator.push(list.get(i));
} else {
while (operator.count != 0&&compare(operator.top(), list.get(i)) >= 0) {
String top = operator.top();
operator.pop();
suffix.add(top);
}
operator.push(list.get(i));
}
}
}
while (operator.count != 0) {
suffix.add(operator.top());
operator.pop();
}
// System.out.println(suffix);
return suffix;
}
public String CalculateReversePolishExpression(String subStr) { //計算逆波蘭表達式
List<String> suffix = createReversePolishExpression(subStr);
Stack<Double> stack = new Stack<Double>();
for (int i = 0; i < suffix.size(); i++)
{
if (!isOperatorType(suffix.get(i)))
{
if(!isVarableType(suffix.get(i)))
{
//在這里要判斷是否為變量
stack.push(Double.valueOf(suffix.get(i))); //是數字的話壓入棧
}
else
{
if(suffix.get(i).equals("A"))
{
Variable("A",1);
stack.push(value);
}
if(suffix.get(i).equals("B"))
{
Variable("B",2);
stack.push(value);
}
}
}
else
{
Double current = stack.top();
stack.pop();
Double previous = null;
if (stack.count != 0) {
previous = stack.top();
stack.pop();
} else {
previous = new Double(0);
}
Double result = calculate(suffix.get(i), previous, current);
stack.push(result);
}
}
return stack.top().toString();
}
public String addEnd(String str, String a) {
StringBuffer buf = new StringBuffer();
buf.append(a); //將a添加到當前字符串的尾部
if (str != null) {
buf.append(str);
}
return buf.toString(); //轉換成字符串形式
}
public boolean isOperatorType(String str) { //判斷操作符類型,如果是"+-*/%^"則返回true
if (str.equals("+") || str.equals("-") || str.equals("*")
|| str.equals("/") || str.equals("^") || str.equals("%")) {
return true;
}
return false;
}
public boolean isVarableType(String str) { //判斷操作符類型,如果是"AB"則返回true
if (str.equals("A") || str.equals("B"))
{
return true;
}
return false;
}
public int compare(String op1, String op2) { //比較操作符的優先級
Integer iop1 = getOperator(op1);
Integer iop2 = getOperator(op2);
return iop1.compareTo(iop2);
}
public Integer getOperator(String op) { //定義操作符優先級
if ("+".equals(op) || "-".equals(op))
{
return new Integer(0);
}
if ("*".equals(op) || "/".equals(op) || "%".equals(op))
{
return new Integer(1);
}
if ("^".equals(op))
{
return new Integer(2);
}
return null;
}
public Double calculate(String op, Double previous, Double current) { //各種符號的計算
if ("+".equals(op))
{
return previous + current;
}
if ("-".equals(op))
{
return previous - current;
}
if ("*".equals(op))
{
return previous * current;
}
if ("/".equals(op))
{
return previous / current;
}
if ("%".equals(op))
{
return previous % current;
}
if ("^".equals(op))
{
return Math.pow(previous, current);
}
return null;
}
public static void main(String[] args) {
String strs = "(2^B+A*B)/3";
BigDecimal result = new CalculateString().calculateString(strs);
System.out.println(result.toString());
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -