计算器代码 ,双栈写法 ,具体内容看注释
package com.zy.demo;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Stack;
/**
* Copyright:www.zhaoyang.wicp.vip
* Author:王昭阳 -小明机器人
* Date:2021/10/11
* Description:代码版权声明
* 这是一个全能计算器代码
* 具体思路如下
* 1.建立两个栈,分别是 数字栈 和符号栈
* 2.从左到有依次遍历表达式
* 3.如果遇到数字,将数字入数字栈
* 4.如果遇到符号,分两种情况,若符号栈为空,该符号直接入符号栈
* 5.若符号栈不为空--继续判断该符号的优先级是否小于或等于该栈顶符号优先级,
* 如果是,则出栈符号栈顶元素,再出栈两次数字栈元素,进行运算(最后出栈的数字放前面),运算出来的结果放入数字栈,然后再5操作一次
* 如果不是,符号直接入符号栈
* 6.最后数字栈剩下最后一个数字,就是结果
*/
public class MainCircleClient {
private static Stack<Double> numList;
private static Stack<String> charList;
public static void main(String[] args) {
// String circleString = "7*2+4+2*4-3";
ArrayList<String> circleList = new ArrayList<>();
circleList.add("7");
circleList.add("-");
circleList.add("2");
circleList.add("/");
circleList.add("4");
circleList.add("+");
circleList.add("3");
numList = new Stack<>();
charList = new Stack<>();
for (int i = 0; i < circleList.size(); i++) {
String s = circleList.get(i);
if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {
if (charList.isEmpty() || getPor(s) > getPor(charList.peek())) {
charList.push(s);
} else if (getPor(s) <= getPor(charList.peek())) {
opera();
if (getPor(s) <= getPor(charList.peek())) {
opera();//防止运算后栈顶的第二个元素也符合判断条件,所以必须再执行一次
}
charList.push(s);
}
} else {
numList.push(Double.parseDouble(s));
}
}
while (numList.size() > 1) {
opera();
}
Double peek = numList.peek();
System.out.println(peek + "结果");
}
public static void opera() {
Double second = numList.pop();
Double first = numList.pop();
String pop = charList.pop();
double answer = getAnswer(first, second, pop);
numList.push(answer);
}
public static int getPor(String opera) {
int por = 0;
if (opera.equals("+")) {
por = 0;
}
if (opera.equals("-")) {
por = 0;
}
if (opera.equals("*")) {
System.out.println("*****");
por = 3;
}
if (opera.equals("/")) {
por = 3;
}
return por;
}
public static double getAnswer(double a, double b, String c) {
double answer = 0;
if (c.equals("+")) {
answer = a + b;
} else if (c.equals("-")) {
answer = a - b;
} else if (c.equals("*")) {
answer = a * b;
} else if (c.equals("/")) {
answer = a / b;
}
return answer;
}
}
网友评论