Kazekage Gaara
Kazekage Gaara

Reputation: 15052

String.split() generates a NullPointerException

String.split() generates a NullPointerException.

BufferedReader brs = new BufferedReader(new InputStreamReader(System.in));
String s1;
String s2[];
s1 = brs.readLine();
s2 = s1.split(" ");

Upvotes: 2

Views: 18737

Answers (6)

bpgergo
bpgergo

Reputation: 16037

if this line throws nullpointer

s2 = s1.split(" ");

then s1 must be null

check for null before you call EDIT split /EDIT

Note: BufferedReader.readLine(); 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

Upvotes: 1

Dmitry Zaytsev
Dmitry Zaytsev

Reputation: 23962

Your BufferedReader is definately empty, so readline() returns null. Maybe your input stream is empty.

Upvotes: 0

Vaandu
Vaandu

Reputation: 4935

s1 might be null. Try this.

if (s1 != null && !s1.trim().equals(""))
    s2 = s1.split(" ");

Upvotes: 2

Buchi
Buchi

Reputation: 1368

BufferedReader.readLine() returns null if the end of stream is encountered. See the javadoc. You should put a null check before you split s1.

Upvotes: 1

Pieter
Pieter

Reputation: 3399

Have you checked what's coming from brs.readLine(). That is where the null-value originates from. Probably the file is empty: http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine%28%29

Upvotes: 1

KV Prajapati
KV Prajapati

Reputation: 94645

s1 might be null,

s1 = brs.readLine();
if(s1!=null)
 s2 = s1.split(" ");

Upvotes: 15

Related Questions