public boolean isItMyName(String name)
{
name = fullname.substring(0,fullname.indexOf(' '));
...
}
Then my code goes on and on. When I run this, I get a null pointer exception and the error is pointing to this line.
I also created a JUnit tester, where it tests whether the input is true or false.
Name myName = new Name();
assertEquals(false, myName.isItMyName("Troll");
It also gives me a null pointer exception at assertEquals(false, myName.isItMyName("Troll"));
I’m at my wit’s end. How do I fix this?
@ Greg Hewgill:
In my Name class, I do this:
public class Name(String n)
{
name = n;
}
But in my main method, I pass in the string: Name myName = new Name(“Johnathy”);
So string isn’t null.
FULLNAME:
public class EmailAddress {
private String address;
public EmailAddress(String a)
{
address = a;
}
public String toString()
{
return address;
}
Well you’re ignoring your parameter… you’re assigning a new value to
namein the first line. That means your method is almost certainly broken to start with.Then consider where
fullname(which I assume is an instance variable) is going to come from. Unless you’re setting it to a value within your parameterless constructor, it’s going to benullby default. Is that really what you want?I suggest you change your
Nameclass to only have constructors taking name parameters, and that you validate that they’re not null. That way you can never have an invalidNameobject, where the full name isnull.EDIT: Now you’ve posted more code, look at your parameterless constructor and the
setNamemethod:That means your parameterless constructor is equivalent to:
… i.e. a no-op.
fullnamewill be null, hence the exception.My advice is to get rid of the parameterless constructor entirely, and make the other one validate the parameter.