我正在尝试将表达式从中缀转换为后缀。我已经尝试调试代码,但是在弹出变量时我不断收到空指针异常。我得到错误的输入是:
(=> (NOT (award)) (badgrade))
我得到错误后的输出是(不是奖励)
请告诉我是否需要编辑 Q 以发布更少的代码/添加更多评论/提供更多信息。谢谢!
public class toInfix1 {
Stack<String> symbol = new Stack<String>();
Stack<String> variable = new Stack<String>();
Stack<String> operator = new Stack<String>();
static String inputfile = "kb2.txt";
ArrayList<String> infix = new ArrayList<String>();
public void toPrefix1() {
try {
File f = new File(inputfile);
FileReader fr = new FileReader(f);
BufferedReader bf = new BufferedReader(fr);
String str;
String kb = "";
while ((str = bf.readLine()) != null) {
Pattern pattern = Pattern.compile("[(]|[)]|<=>|=>|\\w+|^\\s+");
Matcher m = pattern.matcher(str);
//int a = 0;
System.out.println("KB" + kb);
while (m.find()) {
String node1 = m.group();
System.out.println("Node1" + node1);
//If (
if (node1.equals("(")) {
symbol.push(node1);
} else if (node1.equals("OR") || node1.equals("AND")
|| node1.equals("NOT") || node1.equals("=>")
|| node1.equals("<=>")) {
operator.push(node1);
//If )
} else if (node1.equals(")")) {
//Pop symbol (
if(!variable.empty()&& !operator.empty() && !symbol.empty()){
String symbol1 = "", op = "";
if (symbol.peek() != null && !symbol.empty()) {
symbol1 = symbol.pop();
}
//Pop if operator AND OR => <=> (Binary)
if (operator.peek() != null && !operator.empty()) {
op = operator.pop();
if (op.equals("AND") || op.equals("OR")
|| op.equals("=>") || op.equals("<=>")) {
String var2 = "";
String var1 = "";
if (variable.peek() != null && !variable.empty()) {
var1 = variable.pop();
}//Error occurs in the following if condition
if (variable.peek() != null && !variable.empty()) {
var2 = variable.pop();
}
kb = "(" + var1 + op + var2 + ")";
variable.push(kb);
//Pop if operator NOT (Unary)
} else if (op.equals("NOT")) {
String var1 = "";
if (variable.peek() != null && !variable.empty()) {
var1 = variable.pop();
}
kb = "(" + op + var1 + ")";
variable.push(kb);
//No operator after popping )
}
}
}
//If there are no operators
} else {
variable.push(node1);
}
}
}
fr.close();
} catch (Exception e) {
System.err.println("Error thrown" + e.getMessage());
}
}
public static void main(String[] args) {
System.out.println("In new file");
toInfix1 inf1 = new toInfix1();
inf1.toPrefix1();
System.out.println("Completed");
}
}