这个项目有两个类。Main 方法是 Test2,子类是 Stack。这里的错误部分是这部分:
堆栈 s = 新堆栈(20);
每当我运行它时,它都会输出如下:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(Unknown Source)
at com.stack.Test2.prefixToPostfix(Test2.java:31)
at com.stack.Test2.main(Test2.java:18)
如果 Stack 泛型不断响应错误,我应该如何放置“n 个项目”?
主要方法如下:
package com.stack;
import java.util.Stack;
//PREFIX TO POSTFIX
public class Test2 {
public static void main(String[] args) {
String prefix1 = "A + B * C";
System.out.println(prefixToPostfix(prefix1));
}
static String prefixToPostfix(String prefix) {
Stack<String> s = new Stack(100);
String[] tokens = prefix.split(" ");
for (int i = tokens.length-1; i>=0; i--) {
String token = tokens[i];
if (Character.isLetterOrDigit(token.charAt(i))) {
String op1 = s.peek(); s.pop();
String op2 = s.peek(); s.pop();
String exp = op1 + op2 + token;
s.push(exp);
}
else {
s.push(token + " ");
}
}
return s.peek();
}
}
这是 ISEMPTY、ISFULL、PEEK、PUSH 等的堆栈操作。
package com.stack;
public class Stack<T> {
int size;
T A[];
int top = -1;
public Stack(int size) {
this.size = size;
A = (T[]) new Object[size];
top = -1;
}
public void push(T item) {
top++;
A[top] = item;
}
public void pop() {
top--;
}
public boolean isEmpty() {
if(top == - 1) {
return true;
}
return false;
}
public T peek() {
return A[top];
}
}