简体   繁体   English

检查平衡括号-nullPointerException

[英]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. 我在以下代码中的函数areParenthesisBalanced中的s.push(expr.charAt(i))行中获取了NullPointerException。 Please help me understand why is it so? 请帮助我理解为什么会这样吗?

Is it because stack object is initialised to null? 是因为堆栈对象被初始化为null吗?

public class BalancedParenthesisUsingStack { 公共类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} {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) com.practitcePrograms.BalancedParenthesisUsingStack.main(BalancedParenthesis):com.practitcePrograms.BalancedParenthesisUsingStack.main(BalancedParenthesis41)上com.practitcePrograms.BalancedParenthesisUsingStack.areParenthesisBalanced(BalancedParenthesisUsingStack.java:22)的线程“ main”中的java.lang.NullPointerException异常。

您忘记实例化堆栈:

Stack<Character> s = new Stack<>;

For your question: 对于您的问题:

Is it because stack object is initialised to null? 是因为堆栈对象被初始化为null吗? Answer: Yes . 答: 是的

You have to create instance before you use. 您必须先创建实例,然后再使用。

Create new instance using Stack<Character> s = new Stack<>; 使用Stack<Character> s = new Stack<>;创建新实例Stack<Character> s = new Stack<>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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