用Java 实现简单的计算器
由于想转到上层开发,便学习起了Java,《Java语言程序设计-基础篇》这本书挺不错的,挺适合入门。看了几天,今天学到字符串处理这章,看得差不多了便写了计算器这个小程序练习下。
以下为计算器的方法:
public static void calculator(StringBuilder s){ // Define operate priority, must first calculate '*' or '/' // then is '+', '-' String[] operatorPriority = {"(\\d+)(\\*|\\/)(\\d+)", "(\\d+)(\\+|\\-)(\\d+)"}; int currentOperate = 0; Pattern pattern; Matcher matcher; while (true){ // First check if any operator in the statement pattern = Pattern.compile("\\D"); matcher = pattern.matcher(s); // Have match '+', '-', '*', '/' if (matcher.find()){ pattern = Pattern.compile(operatorPriority[currentOperate]); matcher = pattern.matcher(s); if (matcher.find()){ String a = matcher.group(1); String b = matcher.group(2); String c = matcher.group(3); String abc = a + b + c; int i = 0; switch (b){ case "*": i = Integer.parseInt(a) * Integer.parseInt(c); break; case "/": i = Integer.parseInt(a) / Integer.parseInt(c); break; case "+": i = Integer.parseInt(a) + Integer.parseInt(c); break; case "-": i = Integer.parseInt(a) - Integer.parseInt(c); break; } System.out.println(s.replace(s.indexOf(abc), s.indexOf(abc) + abc.length(), i + "")); } else currentOperate++; } else break; } }
版权声明:
作者:bin
链接:https://ay123.net/mystudy/543/
来源:爱影博客
文章版权归作者所有,未经允许请勿转载。
THE END
0
二维码
海报
用Java 实现简单的计算器
由于想转到上层开发,便学习起了Java,《Java语言程序设计-基础篇》这本书挺不错的,挺适合入门。看了几……
共有 0 条评论