0

Full code here: https://pastebin.com/ntSZ3wZZ Okay so something must be going horribly wrong with my constructors in a linkedlist program I am trying to create.

Here is what my program is supposed to do:

// running
add 3.0 3.0 Three
add 2.0 2.0 Two
add 1.0 1.0 One
print
One{0} +1.0, +1.0
Two{0} +2.0, +2.0
Three{0} +3.0, +3.0

Here is what happens:

add 3.0 3.0 Three
Exception in thread "main" java.lang.NullPointerException
        at Pet.setLat(Pet.java:37)
        at Pet.newPet(Pet.java:24)
        at Pet.<init>(Pet.java:18)
        at PetList.insertFront(PetList.java:23)
        at Exe.main(Exe.java:14)

I feel like I am using a null reference (if that's how you call it). But I can't figure out where or how! I know it's a vague question but I don't know how else to ask it. If there is some edits I can make to my question to make it more easy please let me know. Thank you for any help!

Here is some of my code:

public Pet() {
    name = "";
    treats = 0;
    coor = new Coordinate();
}

public Pet(Pet copy) {
    if(copy == null) {
        name = "";
        treats = 0;
        coor = new Coordinate();
        return;
    }
    newPet(copy);
}

public void newPet(Pet copyTwo) {
    setName(copyTwo.name);
    setTreats(copyTwo.treats);
    setLat(copyTwo.getLat()); // error here line 24
    setLong(copyTwo.getLong());
}
public void setLat(float newLat) {
    coor.setLatitude(newLat);
}
Coder117
  • 801
  • 2
  • 9
  • 22

1 Answers1

3

your problem is that your copy-constructor doesn't initialize coor before you call setLat(). Change your public Pet(Pet copy) to:

public Pet(Pet copy) {
    this();
    if(copy != null) {
        newPet(copy);
    }
}
JohnnyAW
  • 2,866
  • 1
  • 16
  • 27
  • Bless your soul. Also, does `this();` just call my default constructor? – Coder117 Apr 20 '17 at 20:02
  • Yes, and it is done impicilty if you neither call another constructor of your class nor one of the super-class (the default-constructor always calls `super()` implicitly if no explicit `this(...)` or `super(...)` call is given). – Turing85 Apr 20 '17 at 20:10