目标不是解析实际整数而是刺激A + B * C,例如输出ABC * +
我不是在使用泛型,而是使用自制的Stack类。我总是以一个错误的结束异常结束,引用peek()方法。我已经尝试了很长一段时间跟踪它,并且无法真正解决出错的问题。
import java.util.*;
public class Stack {
private char[] arr;
private int maxsize;
private int top = -1;
public Stack(int size) {
maxsize = size;
arr = new char[maxsize];
}
public void push(char x) {
arr[++top] = x;
}
public char pop() {
return arr[top--];
}
public char peek() {
return arr[top];
}
public int size() {
return top + 1;
}
public boolean isEmpty() {
return (size() > 0);
}
public boolean isFull() {
return top == maxsize - 1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String text = sc.next();
Stack medo = new Stack(99);
doParse(text);
}
public static void doParse(String text) {
Stack parse = new Stack(900);
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
switch (ch) {
case '-':
case '+':
if (parse.isEmpty()) {
parse.push(ch);
} else {
while (!parse.isEmpty()) {
System.out.print(parse.pop());
}
}
break;
case '*':
case '/':
if (parse.isEmpty() || parse.peek() == '+'
|| parse.peek() == '-') {
parse.push(ch);
} else {
while (!parse.isEmpty()) {
System.out.print(parse.pop());
}
}
;
break;
default:
System.out.print(ch);
}
}
}
}
答案 0 :(得分:2)
你的isEmpty()
方法与它应该做的相反。这导致你偷看空堆栈
public boolean isEmpty() {
return (size() > 0);
}
应该是
public boolean isEmpty() {
return (size() <= 0);
}