//加減乘除 負數、括號這幾種
//具體看代碼以及注釋 (測試沒發現bug,如發現有bug 請指正)
package com.test;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 四則運算,可能不是最優的寫法,自己測試沒發現bug<br>
* 前提:正確的算式,因為沒做算式的驗證<br>
* 思路:<br>
* 1、用正則拆分所有的元素例子:2-5+4*5/(2+2)-4<br>
* 拆分為【2,-5,4,*,5,/,(,2,2,),-4】<br>
* 2、先計算括號里,乘除 ,最后加減
*
* 總結:總體花了17、8個小時 ,主要原因還是沒有仔細總體分析流程導致。<br>
* 以至於想到點寫點代碼、修修改改,沒有一個完整的把握的思路。所以一個問題一定<br>
* 先走通整個思路、流程 其實編碼是最容易的 ,重點是處理的過程思路
*
* @author wangshiyan
* @time 2014-12-4 下午12:50:01
*
*/
public class SizheTool {
public static void main(String[] args) {
try {
System.out.println(jisuanStr("11.2+3.1*(423-(2+5.7*3.4)+5.6)-6.4/(15.5+24)"));
} catch (Exception e) {
System.out.println("請檢查你的算式格式");
e.printStackTrace();
}
}
/**
* 拆分算式里的各個元素並處理對應所在位置<br>
*
* @param str
* @return
*/
public static List<String> splitStr(String string) throws Exception {
List<String> listSplit = new ArrayList<String>();
Matcher matcher = Pattern.compile("\\-?\\d+(\\.\\d+)?|[*/()]|\\-")
.matcher(string);// 用正則拆分成每個元素
while (matcher.find()) {
// System.out.println(matcher.group(0));
listSplit.add(matcher.group(0));
}
return listSplit;
}
/**
* 計算<br>
* 步驟:1、如果有括號<br>
* 然后取上一個最近的(坐標 計算當前括號組合里的算式 ),在繼續往下查找括號 以此類推,直至循環使用到所有坐標元素
* 計算完畢(運算順序括號、乘除、加減)
*
* @param str
* @return
*/
public static double jisuanStr(String str) throws Exception {
double returnDouble = 0;
List<String> listSplit = splitStr(str); // 拆分好的元素
List<Integer> zKuohaoIdxList = new ArrayList<Integer>();// 左括號,<所在坐標,>
if (Pattern.compile(".*\\(|\\).*").matcher(str).find()) {// 如果包含括號運算
String value = "";// 單個字符值
int zIdx = 0;// 上一個左括號在zKuoHaoIdxList的下標
// 此層循環計算完所有括號里的算式
List<String> tempList = new ArrayList<String>();// 前面沒有計算的元素
int removeL = 0;
int tempListSize = 0;
for (int i = 0; i < listSplit.size(); i++) {
value = listSplit.get(i);
tempList.add(value);
tempListSize = tempList.size();
if ("(".equals(value)) {// 左括號
zKuohaoIdxList.add(tempListSize-1);
} else if (")".equals(value)) {// 遇到右括號就計算與上一左括號間的算式
zIdx = zKuohaoIdxList.size() - 1;// 離當前右括號最近的左括號配對
int start = zKuohaoIdxList.get(zIdx);
returnDouble = jisuan(tempList, start + 1, tempListSize-1); // 開始位置,就是上一個左括號
removeL = tempListSize - start;
tempList = removeUseList(tempList, removeL);// 移除已使用的元素
tempList.add(returnDouble + "");// 剛剛計算的值添加進來
zKuohaoIdxList.remove(zIdx);// 計算完畢清除括號
}
}
// 把所有計算完
returnDouble = jisuan(tempList, 0, tempList.size());
} else {// 沒有括號運算
returnDouble = jisuan(listSplit, 0, listSplit.size());
}
return returnDouble;
}
/**
* 倒序刪除已用過的元素
*
* @param list
* @param removeLength
* 數量
* @return
*/
public static List<String> removeUseList(List<String> list, int removeLength) {
int le = list.size() - removeLength;
for (int i = list.size() - 1; i >= le; i--) {
list.remove(i);
}
return list;
}
/**
* 計算算式
*
* @param listSplit
* @param start
* 括號算式開始符位置
* @param end
* 括號結束符位置
* @return
*/
public static double jisuan(List<String> listSplit, int start, int end)
throws Exception {
double returnValue = 0;
String strValue = null;// 臨時變量
List<String> jjValueList = new ArrayList<String>();// 剩下的加減元素
// 遍歷計算乘除法
for (int i = start; i < end; i++) {
strValue = listSplit.get(i);
if ("*".equals(strValue) || "/".equals(strValue)) {// 乘除
strValue = jisuanValue("*".equals(strValue) ? "*" : "/", Double
.parseDouble(jjValueList.get(jjValueList.size() - 1)),
Double.parseDouble(listSplit.get(i + 1)))
+ "";
jjValueList.remove(jjValueList.size() - 1);
i++;
}
jjValueList.add(strValue);
}
// 遍歷計算加減
for (int j = 0; j < jjValueList.size(); j++) {
strValue = jjValueList.get(j);
if ("-".equals(strValue) || "+".equals(strValue)) {
returnValue = jisuanValue("-".equals(strValue) ? "-" : "+",
returnValue, Double.parseDouble(jjValueList.get(j + 1)));
j++;
} else {
returnValue += Double.parseDouble(jjValueList.get(j));
}
}
return returnValue;
}
/**
* 計算2個數間的加減乘除操作 如:2*5 ,2/5
*
* @param type
* 運算符
* @param start
* 數 相當於上面2
* @param end
* 被數 相當於上面5
* @return
*/
public static double jisuanValue(String type, double start, double end)
throws Exception {
double d = 0;
if ("-".equals(type)) {
d = start - end;
} else if ("+".equals(type)) {
d = start + end;
} else if ("*".equals(type)) {
d = start * end;
} else if ("/".equals(type)) {
if (0 == start || 0 == end)
d = 0;
else
d = start / end;
}
return d;
}
}