我正在使用堆栈执行从后缀表达式到后缀表达式的转换。 但是,执行时会发生以下错误:
Exception in thread "main" java.lang.NullPointerException
at Stack.pop(InfixReader.java:108)
at InfixReader.doConversion(InfixReader.java:46)
at InfixReader.main(InfixReader.java:6)
这是一个空指针异常,似乎起源于pop()方法。但是,我无法修复此错误。这是否意味着return语句将返回空值,或者顶部将指向空值。
这是我的代码:
import java.io.*;
public class InfixReader {
public static void main(String[] args) {
InfixReader myAnswer = new InfixReader();
myAnswer.doConversion();
}
public void doConversion() {
String inp[] = readInfix();
Stack post = new Stack();
String n = "";
String ope = "";
int l = inp.length;
for (int i = 0; i < l; i++) {
if (inp[i] != "+" || inp[i] != "-" || inp[i] != "*" || inp[i] != "/" || inp[i] != "^") {
n += inp[i];
} else if (post.empty() == true)
post.push(inp[i]);
else {
boolean id = false;
while (id == false)
ope = post.peek();
if (ope == "^")
n += post.pop();
if (ope == "*" || ope == "/")
if (inp[i] == "*" || inp[i] == "/" || inp[i] == "+" || inp[i] == "-")
n += post.pop();
if (ope == "+" || ope == "-")
if (inp[i] == "+" || inp[i] == "-")
n += post.pop();
if (inp[i] == "^") {
post.push(inp[i]);
id = true;
}
if (inp[i] == "*" || inp[i] == "/")
if (ope == "+" || ope == "-") {
post.push(inp[i]);
id = true;
}
}
}
while (post.empty() != true) {
n += post.pop();
}
evalPostfix(n);
}
public void evalPostfix(String postfix) {
Stack eval = new Stack();
int l = postfix.length();
for (int i = 0; i < l; i++) {
char ch = postfix.charAt(i);
if (ch != '+' || ch != '-' || ch != '*' || ch != '/' || ch != '^') {
eval.push(Character.toString(ch));
} else {
String ch1 = eval.pop();
String ch2 = eval.pop();
int o1 = Integer.parseInt(ch1);
int o2 = Integer.parseInt(ch2);
if (ch == '+')
eval.push(Integer.toString(o1 + o2));
if (ch == '-')
eval.push(Integer.toString(o1 - o2));
if (ch == '*')
eval.push(Integer.toString(o1 * o2));
if (ch == '/')
eval.push(Integer.toString(o1 / o2));
if (ch == '^')
eval.push(Integer.toString(o1 ^ o2));
}
}
System.out.println(eval.pop());
}
public String[] readInfix() {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String inputLine;
try {
System.out.print("Input infix: ");
inputLine = input.readLine();
return inputLine.split(" ");
} catch (IOException e) {
System.err.println("Input ERROR.");
}
// return empty array if error occurs
return new String[]{};
}
}
class Stack {
private int maxSize;
private String[] stackArray;
private int top;
public void MyStack(int s) {
maxSize = s;
stackArray = new String[maxSize];
top = -1;
}
public void push(String j) {
stackArray[++top] = j;
}
public String pop() {
return stackArray[top--];
}
public String peek() {
return stackArray[top];
}
public boolean empty() {
return (top == -1);
}
public boolean isFull() {
return (top == maxSize - 1);
}
}