-
October 31st, 2011, 05:19 PM
#1
[RESOLVED] NullPointer/warnings
why does the toCharArray throw nullpointer?
Code:
String allTxt;
allTxt = br.readLine();
char[] araFull = allTxt.toCharArray();
Last edited by kolt007; October 31st, 2011 at 05:51 PM.
-
November 1st, 2011, 06:48 AM
#2
Re: NullPointer/warnings
Because allTxt is null. Presumably because readline() is returning null.
Always read the API docs so you know what a method does and what values it can return. I'm guessing br is a BufferredReader in which case the API docs say "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"
-
November 1st, 2011, 08:33 AM
#3
Re: NullPointer/warnings
If there is a chance that you might get null pointer then please use use try catch block , in this case it is a null pointer exception.
-
November 1st, 2011, 08:44 AM
#4
Re: NullPointer/warnings
If there is a chance that you might get null pointer then please use use try catch block , in this case it is a null pointer exception.
Generally speaking you should not catch NullPointerException as they are normally thrown because of a coding error ie you are trying to use a reference which you believe is valid but it isn't.
If a variable may be null (eg because, as in this case, the method can return null) you should explicitly test for it not being null before you attempt to use it.
-
November 1st, 2011, 01:10 PM
#5
Re: NullPointer/warnings
I was going to say that exact thing keang +D. Just because, the board instructions call for me to do so.
my solution:
Code:
public static void readOutput() throws IOException{
String allTxt;
int cap;
int read;
try
(BufferedReader br = new BufferedReader(new FileReader(file))) {
allTxt = br.readLine();
cap = allTxt.length();
if(allTxt != null) {
CharArrayWriter caw = new CharArrayWriter(cap);
caw.write(allTxt, 0, cap);
char[] araFull = caw.toCharArray();
// code continues
Last edited by kolt007; November 1st, 2011 at 01:14 PM.
-
November 1st, 2011, 01:46 PM
#6
Re: NullPointer/warnings
Code:
allTxt = br.readLine();
cap = allTxt.length();
if(allTxt != null) {...
Do you really think you've solved the problem with this code?
What's going to happen when the second line runs if allTxt is null?
-
November 1st, 2011, 02:14 PM
#7
Re: NullPointer/warnings
I am missunderstanding unless that if statment returns true it won't run at all?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|