class Main {
public static void main(String[] args) {
System.out.println("Hello world! - java.jsrun.net ");
}
}
import java.util.EmptyStackException;
public class Demo2 {
public static void main(String[] args) {
String exps = "12+8*9-9/3";
int index = 0;
int number1 = 0;
int number2 = 0;
int thiChar = ' ';
StringBuilder sb = new StringBuilder();
ArrayStack numberStack = new ArrayStack(10);
ArrayStack operationStack = new ArrayStack(10);
int result;
for (index = 0; index < exps.length(); index++) {
thiChar = exps.charAt(index);
if (operationStack.isOperation(thiChar)){
if (operationStack.comparePriority(thiChar)){
operationStack.push(thiChar);
}else{
int popChar = operationStack.pop();
number2 = numberStack.pop();
number1 = numberStack.pop();
result = operationStack.calculation(number1, number2, popChar);
operationStack.push(thiChar);
numberStack.push(result);
}
}else{
while (thiChar >= '0' && thiChar <= '9'){
sb.append(thiChar - '0');
System.out.println("拼接字符串"+sb);
index++;
if (index >= exps.length()){
break;
}
thiChar = exps.charAt(index);
}
int num = Integer.parseInt(sb.toString());
numberStack.push(num);
sb = new StringBuilder();
index--;
}
}
while (!operationStack.isEmpty()){
int popChar = operationStack.pop();
number2 = numberStack.pop();
number1 = numberStack.pop();
result = operationStack.calculation(number1,number2,popChar);
numberStack.push(result);
}
System.out.println(numberStack.pop());
}
}
class ArrayStack {
private final int maxSize;
int[] stack;
private int top;
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize];
top = -1;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize - 1;
}
public void push(int i) {
if (isFull()) {
System.out.println("栈满了,请不要再进来了");
return;
}
top++;
stack[top] = i;
}
public int pop() {
if (isEmpty()) {
System.out.println("栈是空的,请不要在进来取了");
throw new EmptyStackException();
}
int retNum = stack[top];
top--;
return retNum;
}
public void traverse() {
for (int thiChar : stack) {
System.out.println(thiChar);
}
}
public int getPriority(int operation) {
if (operation == '*' || operation == '/') {
return 2;
} else if (operation == '+' || operation == '-') {
return 1;
} else if (operation >= '0' && operation <= '9') {
return 0;
} else {
return -1;
}
}
public boolean comparePriority(int operation) {
if (isEmpty()) {
return true;
} else {
int priority1 = getPriority(operation);
int priority2 = getPriority(stack[top]);
return priority1 > priority2;
}
}
public boolean isOperation(int operation) {
return operation == '*' || operation == '/' || operation == '-' || operation == '+';
}
public int calculation(int number1, int number2, int operation) {
switch (operation) {
case '+':
return number1 + number2;
case '-':
return number1 - number2;
case '*':
return number1 * number2;
case '/':
return number1 / number2;
default:
System.out.println(operation);
throw new RuntimeException("符号读取错误!");
}
}
}