# 计算器包括加减乘和括号c语言,计算器算法（支持加减乘除括号）

import java.util.ArrayList;

import java.util.List;

import java.util.Stack;

public class Calculator {

/**

* @param args

*/

public static void main(String[] args) throws Exception {

Listhouzhuishi = houzhui("(0.006+(3-1))/(2+1)+3*2");

//Listhouzhuishi = houzhui("(600+(30000-1))/(2+1)+3*2");

//Double a = Calucate.recursiveCalStr("6+(3-1)/(2+1)+3*2");

System.out.println(calcResult(houzhuishi));

}

public static double calcResult(List houzhishi) throws Exception{

Stack charStack = new Stack();

for (String str : houzhishi) {

if (getHuHao().contains(str)) {

Double data1 = charStack.pop();

Double data2 = charStack.pop();

charStack.push(cal(str.charAt(0),data2,data1));

} else {

charStack.push(Double.valueOf(str));

}

}

return charStack.peek();

}

public static List getHuHao() {

List huhao = new ArrayList(0);

return huhao;

}

public static Double cal(char c,double a,double b) throws Exception{

switch(c){

case '+':

return a+b;

case '-':

return a-b;

case '*':

return a*b;

case '/':

return a/b;

default:

throw new Exception("XX");

}

}

public static List houzhui(String val) {

List result = new ArrayList();

Stack charStack = new Stack();

charStack.push("#");

val = val + "#";

int[][] dir = {

{1,1,0,0,0,1,1},

{1,1,0,0,0,1,1},

{1,1,1,1,0,1,1},

{1,1,1,1,0,1,1},

{0,0,0,0,0,2,-1},

{1,1,1,1,-1,1,1},

{0,0,0,0,0,-1,2},

};

List test = new ArrayList();

StringBuilder temp = new StringBuilder();

for(int i = 0 ,length = val.length(); i < length ; i++) {

String chr = String.valueOf(val.charAt(i));

if (getHuHao().contains(chr) ) {

if (temp.length() > 0) {

}

temp.delete(0, temp.length());

} else {

temp.append(chr);

}

}

for (int i = 0 ,size = test.size(); i < size ; i++) {

String str = test.get(i);

try {

Double.valueOf(str);

} catch (NumberFormatException e) {

int x = getHuHao().indexOf(str);

int y = getHuHao().indexOf(charStack.peek());

if (dir[y][x] == 0) {

charStack.push(str);

} else if (dir[y][x] == 1) {

i --;

} else if (dir[y][x] == 2 && (x == 5 && y == 4 )) {

charStack.pop();

} else if (dir[y][x] == 2 && (x == 6 && y == 6 )) {

break;

} else {

break;

}

}

}

return result;

}

}

• 1
点赞
• 0
收藏
• 0
评论
01-19 2万+
09-17 2万+
05-19 2万+
02-26 5615
03-01 4092
03-29 3万+
08-13 2376
11-18 4061
09-16 1万+

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

©️2022 CSDN 皮肤主题：1024 设计师：我叫白小胖

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。