简体   繁体   中英

Checking balanced Parentheses - nullPointerException

I am getting the NullPointerException in the following code at the line s.push(expr.charAt(i)) in the function areParenthesisBalanced. Please help me understand why is it so?

Is it because stack object is initialised to null?

public class BalancedParenthesisUsingStack {

static Boolean ArePair(char opening, char closing){

    if(opening =='(' && closing == ')') return true;
    else if(opening == '{' && closing == '}') return true;
    else if(opening == '[' && closing == ']') return true;
    return false;
}

static Boolean areParenthesisBalanced(String expr){
    Stack<Character> s = null;

    for(int i =0; i<expr.length();i++){
        Character c = expr.charAt(i);
        if(expr.charAt(i)=='(' || expr.charAt(i)=='[' || expr.charAt(i)=='{'){
            s.push(expr.charAt(i));
        }
        else if (expr.charAt(i)==')' || expr.charAt(i)==']' || expr.charAt(i)=='}'){
            if(s.isEmpty() || (!ArePair(s.peek(), expr.charAt(i)))){
                return false;
            }
            else
            s.pop();

        }
    }
    return s.empty()? true: false;
}

public static void main(String[] args){
    String expression;
    System.out.println("Enter an expression:  "); // input expression from STDIN/Console
     Scanner v = new Scanner(System.in);
    expression = v.nextLine();
    if(areParenthesisBalanced(expression))
        System.out.println("Balanced\n");
    else
        System.out.println("Not Balanced\n");
}

}

Exception : Enter an expression:
{f[f]d}

Exception in thread "main" java.lang.NullPointerException at com.practitcePrograms.BalancedParenthesisUsingStack.areParenthesisBalanced(BalancedParenthesisUsingStack.java:22) at com.practitcePrograms.BalancedParenthesisUsingStack.main(BalancedParenthesisUsingStack.java:41)

您忘记实例化堆栈:

Stack<Character> s = new Stack<>;

For your question:

Is it because stack object is initialised to null? Answer: Yes .

You have to create instance before you use.

Create new instance using Stack<Character> s = new Stack<>;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM