so I have to convert infix to postfix with the example, ab/(c-a)+de. My code did not show any errors only some warnings, it compiled but there is no output. When I run it will show me the message below.
Exception in thread "main" java.lang.NullPointerException
at LinkedStackTest$Convert.convertToPostfix(LinkedStackTest.java:40)
at LinkedStackTest$Convert.main(LinkedStackTest.java:60)
I tried looking over the code multiple times and still do not know what I did wrong. Any help or advice would be great thanks!
My code:
public class LinkedStackTest
{
static class Convert
{
static int getPriority(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
}
return -1;
}
public static String convertToPostfix(String infix)
{
LinkedStack<Character> linkStack = new LinkedStack<>();
String postfix = "";
for (int i = 0; i < infix.length(); i++)
{
char ch = infix.charAt(i);
if (Character.isLetterOrDigit(ch)) {
postfix += ch;
} else if (ch == '(') {
linkStack.push(ch);
} else if (ch == ')') {
while (linkStack.peek() != '(') {
postfix += linkStack.peek();
linkStack.pop();
}
} else {
while (!linkStack.isEmpty() && getPriority(ch) <= getPriority(linkStack.peek())) {
if (linkStack.peek() == '(')
return "Invalid";
postfix += linkStack.peek();
}
linkStack.push(ch);
}
}
while (!linkStack.isEmpty())
{
if(linkStack.peek() == '(')
return "Invalid Expression";
postfix += linkStack.pop();
}
return postfix;
}
public static void main(String[] args) throws Exception
{
String infix = "a*b/(c-a)+d*e";
String postfix = convertToPostfix(infix);
System.out.println("Infix: " + infix);
System.out.println("Postfix: " + postfix);
}
}
}