【项目日记】仿mudou的高并发服务器 --- 实现缓冲区模块,通用类型Any模块,套接字模块
题目
import java.util.Stack;
public class Code {
public int calculate(String s) {
Stack<Integer> data_stack = new Stack<>();
Stack<Character> char_stack = new Stack<>();
int length = s.length();
int i = 0;
while (i < length){
char c = s.charAt(i);
if (c == ' '){
i++;
} else if (checkNumber(c)){
int tmp = 0;
while (i < length && checkNumber(s.charAt(i))){
tmp = tmp * 10 + (s.charAt(i) - '0');
i++;
}
data_stack.push(tmp);
} else if (c == '('){
char_stack.push(c);
i++;
} else if (c == ')'){
while (!char_stack.isEmpty() && char_stack.peek() != '('){
fetchAndCol(data_stack,char_stack);
}
char_stack.pop();
i++;
} else {
if (char_stack.isEmpty() || checkChar(c,char_stack.peek())){
char_stack.push(c);
} else {
while (!char_stack.isEmpty() && !checkChar(c,char_stack.peek())){
fetchAndCol(data_stack,char_stack);
}
char_stack.push(c);
}
i++;
}
}
while (!char_stack.isEmpty()){
fetchAndCol(data_stack,char_stack);
}
return data_stack.pop();
}
public void fetchAndCol(Stack<Integer> data_stack,Stack<Character> char_stack){
Integer pop1 = data_stack.pop();
Integer pop2 = data_stack.pop();
Character pop = char_stack.pop();
Integer math = math(pop1, pop2, pop);
data_stack.push(math);
}
public Integer math(Integer number1,Integer number2,char c){
if (c == '+') return number1 + number2;
if (c == '-') return number2 - number1;
if (c == '*') return number1 * number2;
if (c == '/') return number2 / number1;
else return -1;
}
public boolean checkChar(char c,char top){
if ((c == '*' || c == '/') && (top == '+' || top == '-')) return true;
if (top == '(') return true;
else return false;
}
public boolean checkNumber(char c){
if (c >= '0' && c <= '9') return true;
else return false;
}
}