我在函数areParenthesisBalanced中的s.push(expr.charAt(i))行的以下代码中得到NullPointerException。请帮我理解为什么会这样?
是因为堆栈对象初始化为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");
}
}
例外:输入表达式:
{F [F] d}
线程中的异常&#34; main&#34;显示java.lang.NullPointerException at com.practitcePrograms.BalancedParenthesisUsingStack.areParenthesisBalanced(BalancedParenthesisUsingStack.java:22) at com.practitcePrograms.BalancedParenthesisUsingStack.main(BalancedParenthesisUsingStack.java:41)
答案 0 :(得分:4)
你忘了实例化堆栈:
Stack<Character> s = new Stack<>;
答案 1 :(得分:1)
对于你的问题:
是否因为堆栈对象初始化为null? 答案:是。
您必须在使用前创建实例。
使用创建新实例
Stack<Character> s = new Stack<>;