Checking balanced Parentheses - nullPointerException - java

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)

You forgot to instantiate the Stack :
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<>;

Related

Java Stack error after getting last element via pop method

I have the following code for the solution of Hackerrank.
public static void main(String[] args) {
System.out.println(isBalanced("{(([])[])[]}"));
}
public static String isBalanced(String s) {
Stack<Character> stack = new Stack<>();
stack.push(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
Character c = s.charAt(i);
Character cStack = stack.peek();
if (cStack == '{' && c == '}'
|| cStack == '[' && c == ']'
|| cStack == '(' && c == ')') {
stack.pop();
} else {
stack.push(c);
}
}
if (stack.isEmpty())
return "YES";
return "NO";
}
Although the code seems to working without any problem, it throws the following error on the Hackerrank page. I already test the input in my local IDE as it is {(([])[])[]}, but I am not sure if I need to get the last element (it maybe due to getting it via Character cStack = stack.peek(); and then stack.pop();.
So, could you please have a look at and test this code on Hackerrank page and let me know what is wrong?
Update:
public static String isBalanced(String s) {
Stack<Character> stack = new Stack<>();
stack.push(s.charAt(0));
for (int i = 1; i < s.length(); i++) {
Character c = s.charAt(i);
if (c == '{' || c == '[' || c == '(') {
stack.push(c);
} else if (stack != null) {
Character cStack = stack.peek();
if (cStack == '{' && c == '}'
|| cStack == '[' && c == ']'
|| cStack == '(' && c == ')') {
stack.pop();
}
}
}
if (stack.isEmpty())
return "YES";
return "NO";
}
Before calling stack.peek(), you need to check if the stack is empty or not. Calling pop() or peek() on an empty stack will raise an error.
If the current character is an opening bracket, you don't even need to check the stack top. If it is a closing bracket, then check if the stack is empty or not first. If it is, return false. Otherwise compare the top character and make a decision.

Character stack to check matching brackets no errors but also doesnt appear to do anything

I took a half a year off from programming and now Im just refreshing my memory w super basic little interview questions...and Ive been stuck for 2 days on the first one.. Below is my code can someone just hint to me why the program shows no errors but upon compilation does nothing? It should ignore text characters but Im not even there yet
public class bracketCheck {
public static void main(String[] args) {
Stack <Character> s = new <Character> Stack();
Scanner input = new Scanner(System.in);
String buff;
System.out.println("please enter brackets & text");
buff = input.nextLine();
input.close();
int count = 0;
boolean cont = true;
Character stackTop;
Character current = buff.charAt(count);
do {
if(current == ')' || current== '}' || current== ']') {
s.push(current);
count++;
}
else if(current== '(' || current== '{' || current== '[') {
stackTop = s.pop();
cont = match(stackTop, current);
}
}
while(s.isEmpty() == false /*&& cont =true*/);
if(s.isEmpty())
System.out.println("bout time......");
}
private static boolean match(Character top , Character not) {
if(top == ')' && not == '(')
return true;
else if(top == ']' && not == '[')
return true;
else if(top == '}' && not == '{')
return true;
else
return false;
}
}
I saw some issues in your code, this is my fixed version of it
import java.util.Scanner;
import java.util.Stack;
// use Capital letters in the beginning of class names
public class BracketCheck {
public static void main(String[] args) {
Stack<Character> stack = new Stack<>();
Scanner input = new Scanner(System.in);
String buff;
System.out.println("please enter brackets & text");
buff = input.nextLine();
input.close();
// using java8 makes iterating over the characters of a string easier
buff.chars().forEach(current -> {
// if <current> is an opening bracket, push it to stack
if (current == '(' || current == '{' || current == '[') {
stack.push((char) current);
}
// if <current> is a closing bracket, make sure it is matching an opening
// bracket or alert and return
else if (current == ')' || current == '}' || current == ']') {
if (!match(stack, (char) current)) {
System.out.println("no good");
return;
}
}
});
// if, after we finished iterating the string, stack is empty, all opening
// brackets had matching closing brackets
if (stack.isEmpty()) {
System.out.println("bout time......");
}
// otherwise, alert
else {
System.out.println("woah");
}
}
private static boolean match(Stack<Character> stack, Character closer) {
// if stack is empty, the closer has no matching opener
if (stack.isEmpty()) {
return false;
} else {
// get the most recent opener and verify it matches the closer
Character opener = stack.pop();
if (opener == '(' && closer == ')')
return true;
else if (opener == '[' && closer == ']')
return true;
else if (opener == '{' && closer == '}')
return true;
else
return false;
}
}
}

Java Stack Boolean Output Customization?

So what I have is this slightly modified version of a code that's here a hundred times over for Java Stack Balancing.
import java.util.Stack;
public class Main {
public static String testContent = "{(a,b)}";
public static void main(String args[])
{
System.out.println(balancedParentheses(testContent));
}
public static boolean balancedParentheses(String s)
{
Stack<Character> stack = new Stack<Character>();
for(int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if(c == '[' || c == '(' || c == '{' )
{
stack.push(c);
}else if(c == ']')
{
if(stack.isEmpty()) return false;
if(stack.pop() != '[') return false;
}else if(c == ')')
{
if(stack.isEmpty()) return false;
if(stack.pop() != '(') return false;
}else if(c == '}')
{
if(stack.isEmpty()) return false;
if(stack.pop() != '{') return false;
}
}
return stack.isEmpty();
}
}
What I'd like to do is customize the output such that it would output something like "balanced" or "imbalanced" instead of true/false. Trying to replace return false; with a System.println containing 'balanced' gives me a whole lot of output lines I didn't want. Been searching around here for about an hour and some change and couldn't quite find the answer I was looking for. Any insight?
You could use something like
System.out.println(balancedParentheses(testContent) ? "balanced" : "imbalanced");
OR if you want a method that returns a String wrap the logic in another method
String isBalanced(String expression) {
return balancedParentheses(expression) ? "balanced" : "imbalanced"
}
and in main()
System.out.println(isBalanced(testContent));
Also you could write the code something like this
public static boolean balancedParentheses(String s) {
Stack<Character> stack = new Stack<Character>();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c == '[' || c == '(' || c == '{') {
stack.push(c);
} else if (c == ']' || c == ')' || c == '}') {
if (stack.isEmpty() || !matches(stack.pop(), c))
return false;
}
}
return stack.isEmpty();
}
private static boolean matches(char opening, char closing) {
return opening == '{' && closing == '}' ||
opening == '(' && closing == ')' ||
opening == '[' && closing == ']';
}

Why isn't this program running properly? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
The assignment was to create a postfix to infix converter using Stacks. The program compiles properly but when I tried to make a demo class, I received a null point exception line 32. Please share any observations, better coding conventions, or solutions.
import java.util.Stack;
public class PostfixtoInfix {
private String expression;
private Stack<Character> s;
Character pOpen = new Character('(');
Character pClose = new Character(')');
public String PostfixtoInfix(String e) {
expression = e;
String output = "";
for (int i = 0; i < e.length(); i++) {
char currentChar = e.charAt(i);
if (isOperator(currentChar)) {
while (!s.empty() && s.peek() != pOpen
&& hasHigherPrecedence(s.peek(), currentChar)) {
output += s.peek();
s.pop();
}
s.push(currentChar);
} else if (isOperand(currentChar)) {
output += currentChar;
} else if (currentChar == '(') {
s.push(currentChar);
} else if (currentChar == ')') {
while (!s.empty() && s.peek() != pClose) {
output += s.peek();
s.pop();
}
}
while (!s.empty()) {
output += s.peek();
s.pop();
}
}
return output;
}
public boolean isOperator(char c) {
if (c == '+' || c == '-' || c == '/' || c == '*' || c == '^')
return true;
return false;
}
public boolean isOperand(char c) {
if (c >= '0' && c <= '9')
return true;
if (c >= 'a' && c <= 'z')
return true;
if (c >= 'A' && c <= 'Z')
return true;
return false;
}
public int getOperatorWeight(char operator) {
int weight = -1;
switch (operator) {
case '+':
case '-':
weight = 1;
break;
case '*':
case '/':
weight = 2;
break;
case '^':
weight = 3;
}
return weight;
}
public boolean hasHigherPrecedence(char operator1, char operator2) {
int op1 = getOperatorWeight(operator1);
int op2 = getOperatorWeight(operator2);
if (op1 == op2) {
if (isRightAssociative(operator1))
return false;
else
return true;
}
return op1 > op2 ? true : false;
}
public boolean isRightAssociative(char op) {
if (op == '^')
return true;
return false;
}
}
To fix the NPE initialize your objects. Unlike C++, Stack<Character> s; is equivalent to Stack<Character> s = null;; not to Stack<Character> s = new Stack<>();!
Beware of == and != not behaving as you might expect for boxed objects.
Character a = new Character('A');
Character aa = new Character('A');
System.out.println(a == aa);
gives the (correct!) answer false.
They are different objects. If you want to compare for equality, use either:
System.out.println(a.equals(aa));
System.out.println((char)a==(char)aa);
The first uses an explicit method for comparing the object contents. The second one avoids this problem by using non-object primitives, where equality is bitwise, not reference-equality.
It appears that you declare a private member s, never assign anything to it, and then attempt to use it in expressions like s.empty() and s.pop(). If nothing is ever assigned to s, then it is null, and attempting to call a method on it will result in a NullPointerException.
To create an empty stack, you probably want to change the declaration to:
private Stack <Character> s = new Stack<Character>();
First of all, you have a method looking like a constructor:
public String PostfixtoInfix(String e) {
try changing it to something else, like:
public String transform(String e) {
Second, your s field never gets assigned a stack. Put
s = new Stack<Character>();
in your constructor. Also, new Character('a') != new Character('a'), because that will bypass automatic (pillowweight cached) boxing. Use instead just simple chars as pOpen and pClose.
Your access modifier may be preventing the program to access the stack.
Change:
private Stack <Character> s;
to:
protected Stack <Character> s;
Read more here

Java program to read parenthesis, curly braces, and brackets

I'm supposed to create a Java program which reads expressions that contain, among other items, braces { },
brackets [ ], and parentheses ( ). My program should be properly
nested and that ‘(‘ matches ‘)’, ‘[‘ matches ‘]’, and ‘{’ matches ‘}‘ The
program should be terminated by a ‘$’ at the beginning of an input line.
These are supposed to be sample runs of my program:
Enter an Expression:
A[F + X {Y – 2}]
The expression is Legal
Enter an Expression:
B+[3 – {X/2})*19 + 2/(X – 7)
ERROR—‘]’ expected
Enter an Expression:
()) (
ERROR--‘)’ without ‘(‘
$
I created a class called BalancedExpression and a driver called ExpressionChecker.
I completed my BalancedExpression class. But, I'm having trouble setting up my driver to print out an expression using an InputStreamReader and a BufferedReader. The only thing I was able to figure out was how to terminate my program by letting the user enter a $.
Here is my code so far:
Balanced Expression class:
public class BalancedExpression
{
public BalancedExpression() // Default Constructor
{
sp = 0; // the stack pointer
theStack = new int[MAX_STACK_SIZE];
}
public void push(int value) // Method to push an expression into the stack
{
if (!full())
theStack[sp++] = value;
}
public int pop() // Method to pop an expression out of the stack
{
if (!empty())
return theStack[--sp];
else
return -1;
}
public boolean full() // Method to determine if the stack is full
{
if (sp == MAX_STACK_SIZE)
return true;
else
return false;
}
public boolean empty() // Method to determine if the stack is empty
{
if (sp == 0)
return true;
else
return false;
}
public static boolean checkExpression(String ex) // Method to check Expression in stack
{
BalancedExpression stExpression = new BalancedExpression();
for(int i = 0; i< MAX_STACK_SIZE; i++)
{
char ch = ex.charAt(i);
if(ch == '(' || ch == '{' || ch == '[')
stExpression.push(ch);
else if(ch == ')' && !stExpression.empty() && stExpression.equals('('))
stExpression.pop();
else if(ch == '}' && !stExpression.empty() && stExpression.equals('{'))
stExpression.pop();
else if(ch == ']' && !stExpression.empty() && stExpression.equals('['))
stExpression.pop();
else if(ch == ')' || ch == '}' || ch == ']' )
return false;
}
if(!stExpression.empty())
return false;
return true;
}
private int sp;
private int[] theStack;
private static final int MAX_STACK_SIZE = 6;
}// End of class BalancedExpression
My Driver Program:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExpressionChecker
{
public static void main(String[] args)
{
InputStreamReader reader = new InputStreamReader(System.in);
BufferedReader console = new BufferedReader(reader);
BalancedExpression exp = new BalancedExpression();
String expression = "";
do
{
try{
System.out.print("Enter an Expression: ");
expression = console.readLine();
if("$".equals(expression))
break;
}catch(Exception e){
System.out.println("IO error:" + e);
}
}while(!expression.equals(""));// End of while loop
}
}// End of class ExpressionChecker
Can anyone please help me develop my driver program to print out an output similar to the sample example?
Any help is appreciated. Thanks!
In the if statements in checkExpression method you are using
stExpression.equals()
while what you want to do is to 'peek' at the value on the top of the stack.
Adding simple method that pops the value, pushes it back and returns it should solve the problem(at least this part).
Here is a very short example where you can do the above check very easily :) We have Stack class in Java, it will make the program very easy. Please find below the simple code for this question:
package com.test;
import java.util.Scanner;
import java.util.Stack;
public class StackChar {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enete an expression : ");
String expr = sc.nextLine();
if(checkvalidExpression(expr)){
System.out.println("The Expression '"+expr+"' is a valid expression!!!");
}
else{
System.out.println("The Expression '"+expr+"' is a NOT a valid expression!!!");
}
}
public static boolean checkvalidExpression(String expr){
Stack<Character> charStack = new Stack<Character>();
int len = expr.length();
char exprChar = ' ';
for(int indexOfExpr = 0; indexOfExpr<len; indexOfExpr++){
exprChar = expr.charAt(indexOfExpr);
if(exprChar == '(' || exprChar == '{' || exprChar == '['){
charStack.push(exprChar);
}
else if(exprChar == ')' && !charStack.empty()){
if(charStack.peek() == '('){
charStack.pop();
}
}
else if(exprChar == '}' && !charStack.empty()){
if(charStack.peek() == '{'){
charStack.pop();
}
}
else if(exprChar == ']' && !charStack.empty()){
if(charStack.peek() == '['){
charStack.pop();
}
}
else if(exprChar == ')' || exprChar == '}' || exprChar == ']' ){
return false;
}
}
if(!charStack.empty())
return false;
return true;
}
}

Categories