0

I have been getting a null pointer exception at the split statement. I have initialised all_data1 variable, which when using a split must be an array. Please suggest what am I doing wrong... This is the code for your reference...

    test_cases = t_inp.nextInt();      //input test cases
    for(i=0;i<test_cases;i++)
    {
         String all_data = "";
         all_data = d_inp.readLine();
         all_data1 = all_data.split("\\s+");
         up_bnd[i] = Integer.parseInt(all_data1[i]);
         lw_bnd[i] = Integer.parseInt(all_data1[i+1]);
         Arrays.fill(all_data1, "");
         System.out.println(up_bnd);
         System.out.println(lw_bnd);

    }        
Deepak
  • 1
  • 2
  • 1
    what is the value of `all_data`? – Madhawa Priyashantha Nov 17 '16 at 11:37
  • You'll have to be more specific about what is going into `all_data`, you could be getting the exception because `.readLine()` isn't catching any input so there's nothing to split. – px06 Nov 17 '16 at 11:39
  • Initialize all_data to "" (null character) first, then use readLine() and split... it is possible to there were no line to be read by d_inp and all_data become null and that causes the exception – Sajad Nov 17 '16 at 11:40
  • `readline()` can return **null** if the end of the stream has been reached. – Saurav Sahu Nov 17 '16 at 11:40

1 Answers1

3

It depends on what you get from the the input reading.

I presume you are using BufferedReader, which has readLine.

The javadoc states:

 /**
     * Reads a line of text.  A line is considered to be terminated by any one
     * of a line feed ('\n'), a carriage return ('\r'), or a carriage return
     * followed immediately by a linefeed.
     *
     * @return     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
     *
     * @exception  IOException  If an I/O error occurs
     *
     * @see java.nio.file.Files#readAllLines
     */
    public String readLine() throws IOException {
        return readLine(false);
    }

So either you get a EOL character or your stream has reached his end.

If from your input get new lines, then you could use readLine(boolean ignoreLF) which will ignore EOL characters.

Andrei Sfat
  • 8,440
  • 5
  • 49
  • 69