I’m doing the iTunes U Stanford CS106a course in Java and am loving it but am tearing my hear out over this Name Surfer program.
When I use this code
public NameSurferEntry(String line) {
int endOfName = line.indexOf(" ");
name = line.substring(0,endOfName);
String newLine = line.substring(endOfName+1);
StringTokenizer tokenizer = new StringTokenizer(newLine);
if (tokenizer.hasMoreTokens()) {
name = tokenizer.nextToken();
}
for (int i = 0; tokenizer.hasMoreTokens(); i++) {
array[i] = Integer.parseInt(tokenizer.nextToken());
}
}
I get a Suspended/NullPointerException on the second line (int endOfName, etc.) that says “NameSurferEntry.(String) line: 16”.
If I try to do it this way:
public NameSurferEntry(String line) {
StringTokenizer tokenizer = new StringTokenizer(line);
name = tokenizer.nextToken();
for (int i = 0; tokenizer.hasMoreTokens(); i++) {
array[i] = Integer.parseInt(tokenizer.nextToken());
}
}
I get a Suspended/NullPointerException with the message “StringTokenizer.(String, String, boolean) line: 182” followed by “Source not found.”
Does anybody have any ideas about what I’m doing wrong?
UPDATE
Thanks for the help.
NameSurferEntry is actually called by another class that provides a value for null. But after reading your suggestions I’ve declared line as an ivar but initialized it in the body of NameSurferEntry, and that fixes it. (Before I was both declaring and initializing line as an ivar. I don’t understand why the place I initialize it makes a difference, but there it is.)
The next error isn’t until line 48! So you may hear from me again very soon…. On my way to see whether I can figure it out on my own. Thanks again.
WHOOPS
Not so fast.
When I initialize line to an actual String in the body of NameSurferEntry, everything works out fine.
The problem is that NameSurferEntry is called by another method:
public NameSurferDataBase(String filename) {
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
while (true) {
String blah = br.readLine();
if (blah == null) {
break;
}
NameSurferEntry entry = new NameSurferEntry(blah);
hmap.put(entry.getName(), entry);
}
br.close();
}
catch (IOException ex) {
throw new ErrorException(ex);
}
}
(This method is in turn called by another method that gives it an actual file for filename, so we’re okay there.)
But if I’m passing the parameter blah to NameSurferEntry, and NameSurferEntry then initializes its parameter, then I’ve lost blah, right? My impulse is then to initialize line as an ivar outside of the method, but then I get the NullPointerException message again and I’m back where I started. Argh!
Thoughts?
Your
lineargument is null. That’s why you are getting aNullPointerExceptionwhile trying to operate online(usingindexOfandStringTokenizeronlinewill raise aNullPointerExceptioniflineis null- it has nothing to operate on).