当前位置:网站首页>Stack implementation integrated Calculator - code implementation
Stack implementation integrated Calculator - code implementation
2022-06-30 04:16:00 【If you have a guitar】
Stack implementation calculator - Code implementation
In recent days B I saw an article about stack implementation of integrated calculator on the website , There are some problems in the calculation method bug, It has been improved , recorded , The complete code is as follows :
package com.*.stack;
public class Calculator {
public static void main(String[] args) {
String expression = "1-10*2-18/3-15+3-4";
// Create two stacks , A stack of numbers , A symbol stack
ArrayStack2 numStack = new ArrayStack2(10);
ArrayStack2 operStack = new ArrayStack2(10);
// Define the required related variables
int index = 0;// For scanning
int num1 = 0;
int num2 = 0;
int oper = 0;// Operator
int res = 0;// The result of each calculation
char ch = ' ';// Each scan will get char Save to ch
String keepNum = "";// Define variable strings , For splicing
// Start cyclic scanning expression
while (true){
// In turn expression Every character of 4
ch = expression.substring(index, index + 1).charAt(0);
// Judge ch What is it? , Then do the corresponding treatment
if (operStack.isOper(ch)) {
// If it's an operator
// Judge whether the current symbol stack is empty
if (!operStack.isEmpty()) {
// Determine symbol priority
// boolean flag = true;
while (true) {
if (!operStack.isEmpty()) {
if (operStack.priority(ch) > operStack.priority(operStack.peek())) {
// If the priority of the current operator is higher than that of the stack top operator , Then push directly
operStack.push(ch);
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);// Calculation results
// Put the operation result into the number stack
numStack.push(res);
}else{
// flag = false;
operStack.push(ch);
break;
}
}
} else {
// If it is empty, directly put it on the stack
operStack.push(ch);
}
} else {
// numStack.push(ch - 48);// Because the string intercepts characters , according to ASCII Code table conversion , Need to subtract 48 To get the actual figures , for example '1' -> 1
// When dealing with multi bit numbers , Can not find a number directly into the stack , Because he may be many numbers
// When dealing with , You need to expression The expression of index Then look at another , If it is a number, scan it directly , If it's a symbol, it's on the stack
// Handle multiple bits
keepNum += ch;
// If ch yes expression Last , Then push directly
if (index == expression.length()-1){
numStack.push(Integer.parseInt(keepNum));
} else {
// Determine whether the next character is a number , If it's a number , Just continue scanning , If it's an operator , The stack
if (operStack.isOper(expression.substring(index+1,index+2).charAt(0))) {
numStack.push(Integer.parseInt(keepNum));
keepNum = "";
}
}
}
index++;
if (index >= expression.length()) {
break;
}
}
// When the expression is scanned , From the number stack and symbol stack in sequence pop The corresponding numbers and symbols , And run
while (true) {
// If the symbol stack is empty , It means that the stack has got the final result
if (operStack.isEmpty()){
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);// Calculation results
// Put the operation result into the number stack
numStack.push(res);
}
// Count the last number of stacks pop come out
System.out.printf(" expression %s = %d\n",expression,numStack.pop());
}
}
// Define a ArrayStack Presentation stack
class ArrayStack2 {
private int maxSize; // Define the maximum stack capacity
private int[] stack;// Array simulation stack
private int top = -1;// Define the top of the stack , The initial value is -1
private int base = 1;
// Constructors
public ArrayStack2(int maxSize){
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
// Add a way , You can return the information of the current stack top , But don't take it out , Not really pop
public int peek() {
return stack[top];
}
// Stack full
public boolean isFull(){
return top == maxSize -1;
}
// The stack is empty
public boolean isEmpty(){
return top == -1;
}
// Push --push
public void push(int value){
// First, judge whether the stack is full
if (isFull()){
System.out.println(" Stack full ");
return;
}
top++;
stack[top] = value;
}
// Out of the stack --pop
public int pop(){
if (isEmpty()){
// System.out.println(" The stack is empty ");
throw new RuntimeException(" The stack is empty , No data ");
}
int value = stack[top];
top--;
return value;
}
// Show the stack , Traversal stack
public void list(){
if (isEmpty()){
System.out.println(" The stack is empty , No data ~");
return;
}
// Display data from the top of the stack
for (int i = top; i <= 0; i--) {
System.out.printf("stack[%d]=%d\n",i,stack[i]);
}
}
// // Set the priority of the operator , Show by number
public int priority(int oper){
if(oper == '*' || oper == '/') {
return 1;
} else if (oper == '-' || oper == '+'){
return 0;
} else{
return -1; // Assume that the current expression has only addition, subtraction, multiplication and division
}
}
// Determine whether it is an operator
public boolean isOper(char val){
return val == '+' || val == '-' || val == '*' || val == '/';
}
// computing method
public int cal(int num1, int num2, int oper) {
int res = 0;
switch (oper){
case '+':
res = num1 + num2;
break;
case '-':
res = num2 - num1;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num2 / num1;
break;
default:
break;
}
return res;
}
}
边栏推荐
- Implementation of aut, a self-developed transport layer protocol for sound network -- dev for dev column
- 技术分享| 融合调度中的广播功能设计
- idea灰屏问题
- 使用IDEAL连接数据库,运行出来了 结果显示一些警告,这部分怎么处理
- FortiGate firewall modifies the default timeout of a session
- Pig-Latin (UVA492)
- Smart use of bitmap to achieve 100 million level massive data statistics
- Myrpc version 2
- How to use FME to create your own functional software
- Troubleshooting of abnormal communication between FortiGate and fortiguard cloud
猜你喜欢

The school training needs to make a registration page. It needs to open the database and save the contents entered on the registration page into the database

el-upload上傳文件(手動上傳,自動上傳,上傳進度)

深度融合云平台,对象存储界的“学霸”ObjectScale来了

Day 10 data saving and loading

Redis sentry, persistence, master-slave, hand tear LRU

Thingsboard tutorial (II and III): calculating the temperature difference between two devices in a regular chain

Redis cache avalanche, breakdown and penetration

管道实现进程间通信之命名管道

When easycvr deploys a server cluster, what is the reason why one is online and the other is offline?

(Reprinted) an article will take you to understand the reproducing kernel Hilbert space (RKHS) and various spaces
随机推荐
Error encountered in SQL statement, solve
RPC correction based on arcpy API
Find the interface and add parameters to the form
Unity 在编辑器中输入字符串时,转义字符的输入
在大厂外包呆了三年,颠覆了我的认知!
各位大佬,flink 1.13.6,mysql-cdc2.2.0,抽取上来的datetime(6)类
Technology sharing | broadcast function design in integrated dispatching
Interface testing -- how to analyze an interface?
base64.c
matplotlib. pyplot. Hist parameter introduction
Modifier of JS regular expression
Maya Calendar(POJ1008)
(Reprinted) an article will take you to understand the reproducing kernel Hilbert space (RKHS) and various spaces
Detailed explanation of network layer
Myrpc version 4
errno和perror
thinkphp5实现导入功能
SQLyog导入数据库时报错,求帮解决!
AI落地的新范式,就“藏”在下一场软件基础设施的重大升级里
Pig-Latin (UVA492)