当前位置:网站首页>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;
}
}
边栏推荐
- [cloud native] AI cloud development platform - Introduction to AI model foundry (developers can experience AI training model for free)
- 数据链路层详解
- You know AI, database and computer system
- matplotlib. pyplot. Hist parameter introduction
- Huawei cloud native - data development and datafactory
- Introduction to cloud native + container concept
- base64.c
- Cloud native -- websocket of Web real-time communication technology
- Detailed explanation of network layer
- Graduation project EMS office management system (b/s structure) +j2ee+sqlserver8.0
猜你喜欢

The jupyter notebook kernel hangs up frequently and needs to be restarted

Explain the underlying principles of JVM garbage collection in simple terms

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

Technology sharing | broadcast function design in integrated dispatching

How to use FME to create your own functional software

Huawei cloud native - data development and datafactory

Myrpc version 6

lego_ Reading and summary of loam code

JS inheritance

Linear interpolation of spectral response function
随机推荐
Green new power and "zero" burden of computing power -- JASMINER X4 series is popular
Day 11 script and game AI
OneNote software
JS generator
. Net 7 JWT configuration is too convenient!
第十二天 进阶编程技术
SQL追加字段
Anonymous pipeline for interprocess communication
Interpretation score of bilstm-crf in NER_ sentence
Find the interface and add parameters to the form
Huawei cloud native - data development and datafactory
How to analyze and solve the problem of easycvr kernel port error through process startup?
[Thesis reading | deep reading] role2vec:role based graph embeddings
487-3279(POJ1002)
Project safety and quality
An error occurs when sqlyog imports the database. Please help solve it!
base64.c
Grasp grpc communication framework in simple terms
【模糊神经网络预测】基于模糊神经网络实现水质预测含Matlab源码
FortiGate firewall configuration log uploading regularly