计算器包括加减乘和括号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);

huhao.add("+");

huhao.add("-");

huhao.add("*");

huhao.add("/");

huhao.add("(");

huhao.add(")");

huhao.add("#");

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) {

test.add(temp.toString());

}

test.add(chr);

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);

result.add(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) {

result.add(charStack.pop());

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
    评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:1024 设计师:我叫白小胖 返回首页
评论
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值