java中实现四则运算代码
程序员文章站
2024-03-05 16:44:37
最近上网查了一下,竟然没有找到用java编写的四则运算的代码,就小写了一下.如有问题请大家反馈.
1.说明
代码只是实现了简单的四则运算,支持+,-,*,/,(,) 只...
最近上网查了一下,竟然没有找到用java编写的四则运算的代码,就小写了一下.如有问题请大家反馈.
1.说明
代码只是实现了简单的四则运算,支持+,-,*,/,(,) 只能计算出正确的表达式的值,没有对非法表达式进行校验.
2.实现方法
第一步:将输入的字符串转换为list,主要是用来将string转换为原子:数值/运算符/括号
public list transstr(string str) { list strlist = new arraylist(); /* 获取提出数据的符号串 */ string tmp = str.replaceall("\\d*", ""); /* 记录当前的运算符 */ string curlet = null; /* 记录tmp字符串中第一个运算符的位置 */ int loc = 0; /* 符号串长度 */ int len = tmp.length(); for (int i = 0; i < len; i++) { curlet = tmp.substring(i, i + 1); loc = str.indexof(curlet); /* 如果当前处理字符为( 或者 ) */ if (!"".equals(str.substring(0, loc).trim())) { strlist.add(str.substring(0, loc).trim()); } strlist.add(str.substring(loc, loc + 1)); str = str.substring(loc + 1); } if (0 < str.length()) { strlist.add(str.trim()); } return strlist; }
第二步: 将原来的中缀表达式转换为后缀表达式,在四则运算中,后缀表达式是最方便计算的
public string[] midtoend(list midlist) { stack embl = new stack(); stack result = new stack(); iterator it = midlist.iterator(); string curstr = null; while (it.hasnext()) { curstr = (string) it.next(); /* 确认是否式字符串 */ if(sign.containskey(curstr)) { /* 如果符号栈为空 或者符号为( */ if (0 == embl.size() || "(".equals(curstr)) { embl.push(curstr); } else { /*如果符号为) 符号栈需要出栈,直到匹配一个(为止 */ if(")".equals(curstr)) { while(!"(".equals((string)embl.peek())) { if(0 >= embl.size()) { return null; } result.push(embl.pop()); } embl.pop(); } else { int p1 = integer.parseint((string) sign.get(curstr)); int p2 = integer.parseint((string) sign.get(embl.peek())); /* 如果当前字符的优先级大于栈顶符号的优先级 */ if (p1 > p2) { embl.push(curstr); } else { while (p1 <= p2 || embl.size() > 0) { result.push(embl.pop()); if(0 == embl.size()) { break; } p2 = integer.parseint((string) sign.get(embl.peek())); } embl.push(curstr); } } } } else { result.push(curstr); } } while (0 < embl.size()) { result.push(embl.pop()); } int len = result.size(); string[] ret = new string[len]; for (int i = 0; i < len; i++) { ret[len - i - 1] = (string) result.pop(); } return ret; }
第三步:将解析后缀表达式,返回计算的最终结果
/** * 解析后缀表达式,返回对应的运算结果 * @param string[] endstr 转换后的后缀表达式 * @return object 返回运算结果 如果表达式有误直接打印"input error" */ public object calculate(string[] endstr) { int len = endstr.length; stack calc = new stack(); double p2; double p1; for (int i = 0; i < len; i++) { if (sign.containskey(endstr[i])) { try { p2 = double.parsedouble((string) calc.pop()); p1 = double.parsedouble((string) calc.pop()); calc.push(string.valueof(simplecalc(p1, p2,endstr[i]))); } catch(numberformatexception ex) { ex.printstacktrace(); return "input error"; } catch(exception ex) { ex.printstacktrace(); return "input error"; } } else { calc.push(endstr[i]); } } if (1 == calc.size()) { return calc.pop(); } else { return "input error"; } } /** * 实现底层的运算函数 * @param double p1 数字1 * @param double p1 数字2 * @param string oper 运算符 +-/* */ public double simplecalc(double p1, double p2, string oper) { switch(oper.charat(0)) { case '+': return p1 + p2; case '-': return p1 - p2; case '*': return p1 * p2; case '/': return p1 / p2; default: return p1; } }
第四步:运算符的优先级放在了缓存中进行提取
private static hashmap sign = new hashmap(); /* 将运算符的优先级放入到缓存处理 */ public calculateexp() { sign.put(")", "3"); sign.put("*", "2"); sign.put("/", "2"); sign.put("+", "1"); sign.put("-", "1"); sign.put("(", "0"); }
完整代码
import java.util.arraylist; import java.util.hashmap; import java.util.iterator; import java.util.list; import java.util.stack; /** * java实现计算表达式 * 只实现有加减乘除以及括号的运算 * 例如: 3+12+25*(20-20/4)+10 * @author guobo 2009-3-16 * @version 1.0 */ public class calculateexp { private static hashmap sign = new hashmap(); /* 将运算符的优先级放入到缓存处理 */ public calculateexp() { sign.put(")", "3"); sign.put("*", "2"); sign.put("/", "2"); sign.put("+", "1"); sign.put("-", "1"); sign.put("(", "0"); } /** * @param string 输入的表达式 * @return list 解析后的字符串元素 * 对输入的字符串进行解析 * 转换为需要处理的数据 * 例如:3+12+25*(20-20/4)+10 * 转换后的结果为: * list 元素为 ret = {3,+,12,+,25,*,(,20,-,20,-,20,/,4,),+,10} */ public list transstr(string str) { list strlist = new arraylist(); /* 获取提出数据的符号串 */ string tmp = str.replaceall("\\d*", ""); /* 记录当前的运算符 */ string curlet = null; /* 记录tmp字符串中第一个运算符的位置 */ int loc = 0; /* 符号串长度 */ int len = tmp.length(); for (int i = 0; i < len; i++) { curlet = tmp.substring(i, i + 1); loc = str.indexof(curlet); /* 如果当前处理字符为( 或者 ) */ if (!"".equals(str.substring(0, loc).trim())) { strlist.add(str.substring(0, loc).trim()); } strlist.add(str.substring(loc, loc + 1)); str = str.substring(loc + 1); } if (0 < str.length()) { strlist.add(str.trim()); } return strlist; } /** * 将表达式从中缀表达式转换为后缀表达式(波兰式) * @param list 解析后的表达式的列表 * @return string[] 转换后的表达式字符串数组 */ public string[] midtoend(list midlist) { stack embl = new stack(); stack result = new stack(); iterator it = midlist.iterator(); string curstr = null; while (it.hasnext()) { curstr = (string) it.next(); /* 确认是否式字符串 */ if(sign.containskey(curstr)) { /* 如果符号栈为空 或者符号为( */ if (0 == embl.size() || "(".equals(curstr)) { embl.push(curstr); } else { /*如果符号为) 符号栈需要出栈,直到匹配一个(为止 */ if(")".equals(curstr)) { while(!"(".equals((string)embl.peek())) { if(0 >= embl.size()) { return null; } result.push(embl.pop()); } embl.pop(); } else { int p1 = integer.parseint((string) sign.get(curstr)); int p2 = integer.parseint((string) sign.get(embl.peek())); /* 如果当前字符的优先级大于栈顶符号的优先级 */ if (p1 > p2) { embl.push(curstr); } else { while (p1 <= p2 || embl.size() > 0) { result.push(embl.pop()); if(0 == embl.size()) { break; } p2 = integer.parseint((string) sign.get(embl.peek())); } embl.push(curstr); } } } } else { result.push(curstr); } } while (0 < embl.size()) { result.push(embl.pop()); } int len = result.size(); string[] ret = new string[len]; for (int i = 0; i < len; i++) { ret[len - i - 1] = (string) result.pop(); } return ret; } /** * 解析后缀表达式,返回对应的运算结果 * @param string[] endstr 转换后的后缀表达式 * @return object 返回运算结果 如果表达式有误直接打印"input error" */ public object calculate(string[] endstr) { int len = endstr.length; stack calc = new stack(); double p2; double p1; for (int i = 0; i < len; i++) { if (sign.containskey(endstr[i])) { try { p2 = double.parsedouble((string) calc.pop()); p1 = double.parsedouble((string) calc.pop()); calc.push(string.valueof(simplecalc(p1, p2,endstr[i]))); } catch(numberformatexception ex) { ex.printstacktrace(); return "input error"; } catch(exception ex) { ex.printstacktrace(); return "input error"; } } else { calc.push(endstr[i]); } } if (1 == calc.size()) { return calc.pop(); } else { return "input error"; } } /** * 实现底层的运算函数 * @param double p1 数字1 * @param double p1 数字2 * @param string oper 运算符 +-/* */ public double simplecalc(double p1, double p2, string oper) { switch(oper.charat(0)) { case '+': return p1 + p2; case '-': return p1 - p2; case '*': return p1 * p2; case '/': return p1 / p2; default: return p1; } } /** * 主控函数 */ public static void main(string[] args) { calculateexp ce = new calculateexp(); string tmp = "3+12+25*(20-20/4+10"; string ret = (string) ce.calculate(ce.midtoend(ce .transstr(tmp))); double value = 0; try { value = double.parsedouble(ret); } catch (numberformatexception ex) { system.out.print(ret); } system.out.print(value); } }
以下是其他网友的补充
代码的思路是通过正则判断计算每个最小的计算单元。以下是代码:
import java.math.bigdecimal; import java.util.regex.matcher; import java.util.regex.pattern; /** * 计算器工具类 * @author shuqi * @date 2015-7-23 * @version since 1.0 */ public class calculatorutil { public static bigdecimal arithmetic(string exp){ if(!exp.matches("\\d+")){ string result = parseexp(exp).replaceall("[\\[\\]]", ""); return new bigdecimal(result); }else{ return new bigdecimal(exp); } } /** * 最小计数单位 * */ private static string minexp="^((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\]))[\\+\\-\\*\\/]((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\]))$"; /** * 不带括号的运算 */ private static string noparentheses="^[^\\(\\)]+$"; /** * 匹配乘法或者除法 */ private static string prioroperatorexp="(((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\]))[\\*\\/]((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\])))"; /** * 匹配加法和减法 */ private static string operatorexp="(((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\]))[\\+\\-]((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\])))"; /** * 匹配只带一个括号的 */ private static string minparentheses="\\([^\\(\\)]+\\)"; /** * 解析计算四则运算表达式,例:2+((3+4)*2-22)/2*3 * @param expression * @return */ private static string parseexp(string expression){ //方法进入 先替换空格,在去除运算两边的()号 expression=expression.replaceall("\\s+", "").replaceall("^\\(([^\\(\\)]+)\\)$", "$1"); //最小表达式计算 if(expression.matches(minexp)){ string result=calculate(expression); return double.parsedouble(result)>=0?result:"["+result+"]"; } //计算不带括号的四则运算 if(expression.matches(noparentheses)){ pattern patt=pattern.compile(prioroperatorexp); matcher mat=patt.matcher(expression); if(mat.find()){ string tempminexp=mat.group(); expression=expression.replacefirst(prioroperatorexp, parseexp(tempminexp)); }else{ patt=pattern.compile(operatorexp); mat=patt.matcher(expression); if(mat.find()){ string tempminexp=mat.group(); expression=expression.replacefirst(operatorexp, parseexp(tempminexp)); } } return parseexp(expression); } //计算带括号的四则运算 pattern patt=pattern.compile(minparentheses); matcher mat=patt.matcher(expression); if(mat.find()){ string tempminexp=mat.group(); expression=expression.replacefirst(minparentheses, parseexp(tempminexp)); } return parseexp(expression); } /** * 计算最小单位四则运算表达式(两个数字) * @param exp * @return */ private static string calculate(string exp){ exp=exp.replaceall("[\\[\\]]", ""); string number[]=exp.replacefirst("(\\d)[\\+\\-\\*\\/]", "$1,").split(","); bigdecimal number1=new bigdecimal(number[0]); bigdecimal number2=new bigdecimal(number[1]); bigdecimal result=null; string operator=exp.replacefirst("^.*\\d([\\+\\-\\*\\/]).+$", "$1"); if("+".equals(operator)){ result=number1.add(number2); }else if("-".equals(operator)){ result=number1.subtract(number2); }else if("*".equals(operator)){ result=number1.multiply(number2); }else if("/".equals(operator)){ //第二个参数为精度,第三个为四色五入的模式 result=number1.divide(number2,5,bigdecimal.round_ceiling); } return result!=null?result.tostring():null; } }
代码原本是一个博客,原来代码没有注释而且存在bug,我稍微修稿了一哈添加了注释。在这里做个笔记,方便以后用
另为表示对原作者的敬意,附上原始代码
/** * 四则运算表达式计算 * @author penli * */ public class arithmetic { public static void main(string args[]){ system.out.println(arithmetic("2.2+((3+4)*2-22)/2*3.2")); } public static double arithmetic(string exp){ string result = parseexp(exp).replaceall("[\\[\\]]", ""); return double.parsedouble(result); } /** * 解析计算四则运算表达式,例:2+((3+4)*2-22)/2*3 * @param expression * @return */ public static string parseexp(string expression){ //string numberreg="^((?!0)\\d+(\\.\\d+(?<!0))?)|(0\\.\\d+(?<!0))$"; expression=expression.replaceall("\\s+", "").replaceall("^\\((.+)\\)$", "$1"); string checkexp="\\d"; string minexp="^((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\]))[\\+\\-\\*\\/]((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\]))$"; //最小表达式计算 if(expression.matches(minexp)){ string result=calculate(expression); return double.parsedouble(result)>=0?result:"["+result+"]"; } //计算不带括号的四则运算 string noparentheses="^[^\\(\\)]+$"; string prioroperatorexp="(((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\]))[\\*\\/]((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\])))"; string operatorexp="(((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\]))[\\+\\-]((\\d+(\\.\\d+)?)|(\\[\\-\\d+(\\.\\d+)?\\])))"; if(expression.matches(noparentheses)){ pattern patt=pattern.compile(prioroperatorexp); matcher mat=patt.matcher(expression); if(mat.find()){ string tempminexp=mat.group(); expression=expression.replacefirst(prioroperatorexp, parseexp(tempminexp)); }else{ patt=pattern.compile(operatorexp); mat=patt.matcher(expression); if(mat.find()){ string tempminexp=mat.group(); expression=expression.replacefirst(operatorexp, parseexp(tempminexp)); } } return parseexp(expression); } //计算带括号的四则运算 string minparentheses="\\([^\\(\\)]+\\)"; pattern patt=pattern.compile(minparentheses); matcher mat=patt.matcher(expression); if(mat.find()){ string tempminexp=mat.group(); expression=expression.replacefirst(minparentheses, parseexp(tempminexp)); } return parseexp(expression); } /** * 计算最小单位四则运算表达式(两个数字) * @param exp * @return */ public static string calculate(string exp){ exp=exp.replaceall("[\\[\\]]", ""); string number[]=exp.replacefirst("(\\d)[\\+\\-\\*\\/]", "$1,").split(","); bigdecimal number1=new bigdecimal(number[0]); bigdecimal number2=new bigdecimal(number[1]); bigdecimal result=null; string operator=exp.replacefirst("^.*\\d([\\+\\-\\*\\/]).+$", "$1"); if("+".equals(operator)){ result=number1.add(number2); }else if("-".equals(operator)){ result=number1.subtract(number2); }else if("*".equals(operator)){ result=number1.multiply(number2); }else if("/".equals(operator)){ result=number1.divide(number2); } return result!=null?result.tostring():null; } }
最后给大家分享一个网友的实现方法,个人感觉也很不错
import java.util.stack; /** * 利用栈,进行四则运算的类 * 用两个栈来实现算符优先,一个栈用来保存需要计算的数据numstack,一个用来保存计算优先符pristack * * 基本算法实现思路为:用当前取得的运算符与pristack栈顶运算符比较优先级:若高于,则因为会先运算,放入栈顶; * 若等于,因为出现在后面,所以会后计算,所以栈顶元素出栈,取出操作数运算; * 若小于,则同理,取出栈顶元素运算,将结果入操作数栈。各个优先级'(' > '*' = '/' > '+' = '-' > ')' * */ public class operate { private stack<character> pristack = new stack<character>();// 操作符栈 private stack<integer> numstack = new stack<integer>();;// 操作数栈 /** * 传入需要解析的字符串,返回计算结果(此处因为时间问题,省略合法性验证) * @param str 需要进行技术的表达式 * @return 计算结果 */ public int caculate(string str) { // 1.判断string当中有没有非法字符 string temp;// 用来临时存放读取的字符 // 2.循环开始解析字符串,当字符串解析完,且符号栈为空时,则计算完成 stringbuffer tempnum = new stringbuffer();// 用来临时存放数字字符串(当为多位数时) stringbuffer string = new stringbuffer().append(str);// 用来保存,提高效率 while (string.length() != 0) { temp = string.substring(0, 1); string.delete(0, 1); // 判断temp,当temp为操作符时 if (!isnum(temp)) { // 1.此时的tempnum内即为需要操作的数,取出数,压栈,并且清空tempnum if (!"".equals(tempnum.tostring())) { // 当表达式的第一个符号为括号 int num = integer.parseint(tempnum.tostring()); numstack.push(num); tempnum.delete(0, tempnum.length()); } // 用当前取得的运算符与栈顶运算符比较优先级:若高于,则因为会先运算,放入栈顶;若等于,因为出现在后面,所以会后计算,所以栈顶元素出栈,取出操作数运算; // 若小于,则同理,取出栈顶元素运算,将结果入操作数栈。 // 判断当前运算符与栈顶元素优先级,取出元素,进行计算(因为优先级可能小于栈顶元素,还小于第二个元素等等,需要用循环判断) while (!compare(temp.charat(0)) && (!pristack.empty())) { int a = (int) numstack.pop();// 第二个运算数 int b = (int) numstack.pop();// 第一个运算数 char ope = pristack.pop(); int result = 0;// 运算结果 switch (ope) { // 如果是加号或者减号,则 case '+': result = b + a; // 将操作结果放入操作数栈 numstack.push(result); break; case '-': result = b - a; // 将操作结果放入操作数栈 numstack.push(result); break; case '*': result = b * a; // 将操作结果放入操作数栈 numstack.push(result); break; case '/': result = b / a;// 将操作结果放入操作数栈 numstack.push(result); break; } } // 判断当前运算符与栈顶元素优先级, 如果高,或者低于平,计算完后,将当前操作符号,放入操作符栈 if (temp.charat(0) != '#') { pristack.push(new character(temp.charat(0))); if (temp.charat(0) == ')') {// 当栈顶为'(',而当前元素为')'时,则是括号内以算完,去掉括号 pristack.pop(); pristack.pop(); } } } else // 当为非操作符时(数字) tempnum = tempnum.append(temp);// 将读到的这一位数接到以读出的数后(当不是个位数的时候) } return numstack.pop(); } /** * 判断传入的字符是不是0-9的数字 * * @param str * 传入的字符串 * @return */ private boolean isnum(string temp) { return temp.matches("[0-9]"); } /** * 比较当前操作符与栈顶元素操作符优先级,如果比栈顶元素优先级高,则返回true,否则返回false * * @param str 需要进行比较的字符 * @return 比较结果 true代表比栈顶元素优先级高,false代表比栈顶元素优先级低 */ private boolean compare(char str) { if (pristack.empty()) { // 当为空时,显然 当前优先级最低,返回高 return true; } char last = (char) pristack.lastelement(); // 如果栈顶为'('显然,优先级最低,')'不可能为栈顶。 if (last == '(') { return true; } switch (str) { case '#': return false;// 结束符 case '(': // '('优先级最高,显然返回true return true; case ')': // ')'优先级最低, return false; case '*': { // '*/'优先级只比'+-'高 if (last == '+' || last == '-') return true; else return false; } case '/': { if (last == '+' || last == '-') return true; else return false; } // '+-'为最低,一直返回false case '+': return false; case '-': return false; } return true; } public static void main(string args[]) { operate operate = new operate(); int t = operate.caculate("(3+4*(4*10-10/2)#"); system.out.println(t); } }