当前位置:网站首页>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;
}
}
边栏推荐
- idea灰屏问题
- JS inheritance
- [cloud native] AI cloud development platform - Introduction to AI model foundry (developers can experience AI training model for free)
- I spent three years in a big factory outsourcing, which subverted my understanding!
- Do280 private warehouse persistent storage and chapter experiment
- 网络层详解
- [fuzzy neural network prediction] water quality prediction based on fuzzy neural network, including Matlab source code
- 2021-07-14
- Collinearity problem
- Myrpc version 1
猜你喜欢

FortiGate firewall configuration log uploading regularly

Configure specific source IP in SLA detection of FortiGate sdwan

FortiGate firewall quick initialization administrator password

Huawei cloud native - data development and datafactory

在大厂外包呆了三年,颠覆了我的认知!

AI落地的新范式,就“藏”在下一场软件基础设施的重大升级里
![Blue Bridge Cup: magic cube rotation [Vocational group]](/img/ba/aeae2744f3aaa1052b5af452f990e2.jpg)
Blue Bridge Cup: magic cube rotation [Vocational group]

第九天 脚本與資源管理

Geometric objects in shapely

Node red series (28): communication with Siemens PLC based on OPC UA node
随机推荐
Thingsboard tutorial (II and III): calculating the temperature difference between two devices in a regular chain
Day 10 data saving and loading
Linear interpolation of spectral response function
Default value of JS parameter
[fuzzy neural network prediction] water quality prediction based on fuzzy neural network, including Matlab source code
Technology sharing | broadcast function design in integrated dispatching
两个月拿到N个offer,什么难搞的面试官在我这里都不算事
Es2019 key summary
Myrpc version 6
Clients accessing the daytime service (TCP)
Cloud native -- websocket of Web real-time communication technology
MySQL DDL change
网络层详解
Interpretation score of bilstm-crf in NER_ sentence
Myrpc version 2
Slam mapping, automatic navigation and obstacle avoidance based on ROS (bingda robot)
工程安全和工程质量
Everyone, Flink 1.13.6, mysql-cdc2.2.0, the datetime (6) class extracted
OneNote software
数据链路层详解