2

Getting NullPointerException when it tries to access stones[0].length. Please Help. I have already Initialized Stones Object.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class Solution
    {
public static void main(String args[]) throws IOException
    {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    Scanner sc = new Scanner(System.in);
    int times = sc.nextInt();

    String stones[] = new String[times];
    int score = 0;
        int counter;

    for(int tcase = 0; tcase < times; tcase++)
        stones[tcase] = br.readLine();

      int s = stones[0].length();
        for (int i = 0; i < s ; i++) {
          char j = stones[0].charAt(i);
            counter = 0;
            for (int k = 1; k < times; k++) {
                char aa[] = stones[k].toCharArray();
                for (int l = 0; l <aa.length ; l++) {
                    if(aa[l]==j)
                    {
                        counter++;
                        break;

                    }
                }
                if (counter==times-1) {
                    score++;
                }
            }
        }

    System.out.println(score);
    }
    }

Getting NullPointerException when I try to access stones[0].length(). Please help

  • 2
    possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – DavidPostill Jul 19 '14 at 21:22
  • 5
    Weird, I did copy your code, run it and I do not get any exception. What is your input? – libik Jul 19 '14 at 21:24
  • it's actually a program from HackerRank. Its working correctly when i run it in my laptop. The problem arises when i try to submit it. – Abhishek Singh Jul 19 '14 at 21:28
  • input is for example 3 abcde ccbde cbgde – Abhishek Singh Jul 19 '14 at 21:29
  • 1
    the problem arises because there's no System.in (when you submit) to provide any input, and your array is likely not initialized properly – Ryan J Jul 19 '14 at 21:29
  • Why do you have two objects which handle `System.in` (`BufferedReader` and `Scanner`). Scanner also has method to read entire line `nextLine` but for data like `3 abcde ccbde cbgde` you should use `next` instead. – Pshemo Jul 19 '14 at 21:33
  • 2
    If there is no input, `br.readLine()` will return `null` and you will get an NPE. – Peter Lawrey Jul 19 '14 at 21:37

3 Answers3

2

When you submit your code through some automated service, it's running your code and it's failing because there's no System.in stream to provide any valid data. If you attempt to check for valid data before doing anything, it will catch this condition, and should let you submit, while still working properly on your laptop.

Try this:

Scanner sc = new Scanner(System.in);
int times = 0;

if ( sc.hasNext() ) {   // check to make sure there's valid input first
    times = sc.nextInt();


    String stones[] = new String[times];
    int score = 0;
        int counter;

    for(int tcase = 0; tcase < times; tcase++)
        stones[tcase] = br.readLine();

    if ( stones[0] != null ) {  // check to make sure your array object exists
        int s = stones[0].length();
        for (int i = 0; i < s ; i++) {
            char j = stones[0].charAt(i);
            counter = 0;
            for (int k = 1; k < times; k++) {
                char aa[] = stones[k].toCharArray();
                for (int l = 0; l <aa.length ; l++) {
                    if(aa[l]==j)
                    {
                        counter++;
                        break;
                    }
                }
                if (counter==times-1) {
                    score++;
                }
            }
        }
    }
}
Ryan J
  • 8,275
  • 3
  • 25
  • 28
1

The best way to make sense of these sort of problems is to use a debugger. But just for fun, let's do some code analysis...

int s = stones[0].length();

What can be generating a NullPointerException on this line? Well, the stones variable could be referring to null. We can easily rule this out, however, as the stones variable was assigned a new array instance further up in the code, and was never reassigned before reaching the problem line. The only other possibility is that the array component variable stones[0] refers to null.

Why might stones[0] be null? Well, for starters, it's initialized that way, so if you never assign to that component, then it will be null. However, the for loop that you have between array initialization and the problem line is iterating over all of the array components and initializing them, so every component will be assigned to. What else might be the problem?

The loop is assigning to each array component the value returned by br.readLine(). Could that return value possibly be null? Let's take a look at the javadocs...indeed, we find (emphasis added):

Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached

And there you have it, it is certainly possible for stones[0] to be null! Now, if that is true, what does it mean? Well, it means that the very first call to br.readLine() returned null, signalling that it had reached the end of the stream. Which fits with what other answerers have noted - if System.in() is not available to provide any data, it would make sense to encounter the 'end of stream' condition right out of the gate.

Kevin K
  • 9,344
  • 3
  • 37
  • 62
0

It works with me, although I would not use two stream readers(a Scanner and a BufferedReader) for the same input.

What is the input that causes the exception?

PS. You should close the Scanner when it is not used.

Mateva
  • 786
  • 1
  • 8
  • 27