栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java实现计算器的代码

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java实现计算器的代码

用Java实现的计算器,原理看代码注释,具体内容如下

public class MyCalculator {

 public static void main(String[] args) {
 String obj = "6+(8/2)+6/3+1*8 + 30";
 ArrayList arrayList = strFormat(obj);
 System.out.println(obj + "=" + calculator(arrayList));
 }


 
 private static int calculator(ArrayList obj) {
 ArrayList result = transform(obj);
 System.out.println(result);
 Stack stack = new Stack<>();

 for (int i = 0; i < result.size(); i++) {
  String symbol = result.get(i);
  if (isDigital(symbol)) { //数字直接入栈
  stack.push(Integer.parseInt(symbol));
  } else { // 处理操作符
  int num1, num2;
  num1 = stack.pop(); //取出两个数
  num2 = stack.pop();
  switch (symbol) {
   case "+":
   stack.push(num2 + num1);
   break;
   case "-":
   stack.push(num2 - num1);
   break;
   case "*":
   stack.push(num2 * num1);
   break;
   case "/":
   stack.push(num2 / num1);
   break;
   default:
   break;
  }
  }
 }
 return stack.pop();
 }

 
 private static ArrayList transform(ArrayList arrayList) {
 Stack stack = new Stack<>();
 ArrayList result = new ArrayList<>();
 for (int index = 0; index < arrayList.size(); index++) {
  String symbol = arrayList.get(index);
  if (isDigital(symbol)) { //如果是数字直接输出
  result.add(symbol);
  } else if (symbol.equals(")")) {
  String tmp;
  while (!(tmp = stack.pop()).equals("(")) { // 匹配成功后停止
   result.add(tmp);
  }
  } else {
  if (stack.isEmpty()) {
   stack.push(symbol);
   continue;
  }
  String tmp = stack.peek();
  while (outPriority(symbol) <= inPriority(tmp)) { //优先级小于栈内优先级,一直出栈
   result.add(tmp);
   stack.pop();
   if (stack.isEmpty()) {
   break;
   }
   tmp = stack.peek();
  }
  stack.push(symbol);
  }
 }
 //将剩余的出栈
 while (!stack.isEmpty()) {
  result.add(stack.pop());
 }
 return result;
 }

 
 private static ArrayList strFormat(String src) {
 if (src == null || src.equals("")) {
  return null;
 }
 ArrayList arrayList = new ArrayList<>();
 StringBuilder comChar = new StringBuilder();
 for (int i = 0; i 

以上全部为本篇文章的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/140666.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号