用Java实现栈和综合计算器:详细步骤及代码示例(附图解)
最编程
2024-08-03 09:02:18
...
import java.util.Scanner;
import java.util.Stack;
/**
* @author 兴趣使然黄小黄
* @version 1.0
* 简单计算器实现
*/
@SuppressWarnings({"all"})
public class Calculator {
public static void main(String[] args) {
//接收表达式
System.out.println("请输入表达式: ");
Scanner scanner = new Scanner(System.in);
String expression = scanner.next();
//创建一个数栈 一个符号栈
Stack<Integer> numStack = new Stack<>();
Stack<Integer> operStack = new Stack<>();
//定义变量
int index = 0; //用于扫描
int num1 = 0;
int num2 = 0;
int oper = 0;
int res = 0;
char ch = ' '; //每次扫描的char保存
String keepNum = ""; //用于保存多位数字进行拼接
//扫描计算
while (true){
//依次得到expression每一个字符
ch = expression.substring(index, index+1).charAt(0);
//判断ch进行相应的处理
if (isOper(ch)){
//如果是运算符
if (operStack.isEmpty()){
//判断当前的符号栈是否为空,若为空直接入栈
operStack.push((int)ch);
}else {
//符号栈不为空
//若当前操作符优先级小于等于栈中的操作符
if (priority(ch) <= priority(operStack.peek())){
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = cal(num1, num2, oper);
//将运算结果入数栈
numStack.push(res);
//将当前的操作符入符号栈
operStack.push((int) ch);
}else {
operStack.push((int) ch);
}
}
}else {
//如果是数字直接入数栈
//需要考虑多位数的情况
//如果当前位置为数字,则继续向后看,直到为符号或者遍历完成为止
//已经查看的数字进行字符串拼接,即为正确的数字
keepNum += ch;
//如果已经到末尾,则直接入栈
if (index == expression.length()-1){
numStack.push(Integer.parseInt(keepNum));
}else {
//判断下一个字符是否为数字,若是则继续扫描,不是则直接入栈
if (isOper(expression.substring(index+1, index+2).charAt(0))){
numStack.push(Integer.parseInt(keepNum)); //1的ascII码为49,而ch为字符
keepNum = "";
}
}
}
//index+1 并判断是否扫描完毕
index++;
if (index >= expression.length()){
break;
}
}
//表达式扫描完毕过后,顺序的从数栈和符号栈取出对应的数字和符号进行运算
//最后数栈只剩的一个数字为结果
//也可以判断符号栈是否为空,如果为空则说明数栈只剩一个数
while (numStack.size() > 1){
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = cal(num1, num2, oper);
numStack.push(res);
}
//打印结果
System.out.println("结果: " + numStack.pop());
}
//返回运算符号的优先级,返回数字越大,优先级越大
public static int priority(int operation){
if (operation == '*' || operation == '/'){
return 1;
}else if (operation == '+' || operation == '-'){
return 0;
}else {
return -1;
}
}
//判断是否为运算符
public static boolean isOper(char val){
return val == '+' || val == '-' || val == '/' || val == '*';
}
//计算方法
public static int cal(int num1, int num2, int operation){
int res = 0; //存放返回的结果
switch (operation){
case '+':
res = num1 + num2;
break;
case '-':
res = num2 - num1;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num2 / num1;
break;
default:
break;
}
return res;
}
}