I hope you doing well =)
I'm new to Java and currently, I started learning OOP not a long time ago.
I have a task with which I have a problem.
Add a setter for the name field so that if someone typed an empty value in the name field, or a value greater than 100 characters, then this call to the setter would be ignored, and the old value would be typed in the name field.
The first time I did this with the following code everything was fine when I ran it in Eclipse.
But when I ran it in the test app, it failed because for example the setName method on the input "dyqu" is setting the value of the "Walker" name field, and it should have been set to "dyqu".
public class SpaceShip {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
if(this.name == null)
this.name = name;
}
//Test output
public static void main(String[] args) {
SpaceShip ship = new SpaceShip();
ship.setName("Walker");
System.out.println(ship.getName()); //Should be Walker
ship.setName("");
System.out.println(ship.getName()); //Should be Walker, empty value ignored
ship.setName("Voyager ".repeat(100));
System.out.println(ship.getName()); //Should be Walker, too long value ignored
}
}
Then I tried to change the code to this one:
public void setName(String name) {
if(this.name.length() < 0 && this.name.length() > 100)
this.name = name;
}
I got this error:
Exception in thread "main" java.lang.NullPointerException
at SpaceShip.setName(SpaceShip.java:9)
at SpaceShip.main(SpaceShip.java:16)
Unfortunately, I can't solve the issue on lines 9 and 16.
The input data for line 16 may change. I would be glad for a hint or advice. Thank you!
I solved this issue with the next code, thanks, everyone!
public void setName(String name) {
if (!name.isBlank() && name.length() < 100) {
this.name = name;
}
}