0

In this code, I've been trying to figure out my mistake, when I run it the program crashes. It's asking the user to enter a pet gender, if the user enters (F, f, Female or female) it sets the variable as "Female". same for Male.

I feel it's a silly mistake, but I really couldn't find it!

 public void setPetGender(String PetGender) {

    if (PetGender.toUpperCase().startsWith("F")) //retrun Female if it statrts with letter F, (F,f,Female,female) entered by user.
    {
        PetGender = "Female";
        this.PetGender = PetGender;
    } 
    else  if (PetGender.toUpperCase().startsWith("M")) {
        PetGender = "Male";
        this.PetGender = PetGender;

    } else {
        throw new IllegalArgumentException("The gender your entered is invalid, please enter Female or Male only.");
    }

}
SamiaYM
  • 27
  • 1
  • 8
  • Explain "program crashes" – Stewart Apr 10 '16 at 22:29
  • 1
    By the way, a couple of style points. (1) It is normal for variables to begin with a lowercase latter, so your string should be `petGender` (2) It is considered bad style to set the object which is passed as an arg to a method. Why not just set `this.petGender` directly? – Stewart Apr 10 '16 at 22:31
  • got this, Exception in thread "main" java.lang.NullPointerException at pPet.setPetGender(Pet.java:65) at pPet.(Pet.java:23) Java Result: 1 – SamiaYM Apr 10 '16 at 22:32
  • Style points will be considered, thanks. (2) I tried it before and got the same error – SamiaYM Apr 10 '16 at 22:35
  • 2
    Considering that you have described an NPE, then this implies the variable you're passing through to this method is `null`. If you can demonstrate that the answers in the linked duplicate cannot help you, let me know and I'll cast a reopen vote. – Makoto Apr 10 '16 at 22:37
  • It would seem you call `setPetGender(null)` from your constructor, and `setPetGender()` cannot handle a `null` parameter, as it is currently written. If you want `this.PetGender` to be null in the constructor, do nothing. It's null by default. – Andreas Apr 10 '16 at 22:42

0 Answers0