0

Im trying to add a dog (nyHund) which is created in a different class, to an Arraylist i created using a constructor in another class, but whenever i try to use the Arraylist in the "register" class, im getting the error that the arraylist name can't be resolved.

First class:

    public class Hund {

    private String namn;
    private int ålder;
    private double vikt;
    private String ras;

    public Hund(String hundnamn, int hundålder, String hundras, double hundvikt) {
        this.namn = hundnamn;
        this.ålder = hundålder;
        this.ras = hundras;
        this.vikt = hundvikt;
    }

    public String getNamn() {
        return namn;
    }

    public int getÅlder() {
        return ålder;
    }

    public double getSvanslängd() {
        if (ras=="tax"){
            return 3.7;
        }else{
            return ((vikt*ålder)/10);
        }
    }

    public String toString() {
        return namn + "\n" + ålder + "\n"+ras+"\n"+vikt+"\n"+getSvanslängd();
    }
}

Second Class

    import java.util.ArrayList;
public class testning {

    public static void main(String[] args) {
        Hund nyHund = new Hund("Daisy", 13, "labrador", 22.3);
        System.out.println(nyHund.toString());
        Register.läggTillHund(nyHund);



    }

}

And the Third class:

import java.util.ArrayList;

public class Register {



    public static void läggTillHund(Hund nyHund){
        hundRegister.add(nyHund);
        System.out.println(nyHund);



    }



    private Register(){
        ArrayList<Hund> hundRegister = new ArrayList<Hund>();
    }


}

The problem i am experiencing is with "hundRegister.add(nyHund)"

any thoughts? or pointers where im going wrong? (very new at Java)

Best Regards Oskar

Oskar
  • 11
  • 1

1 Answers1

3

The ArrayList you've created is local to your Register constructor. Declare it inside the class, but outside the constructor, as an instance variable, so it's in scope throughout the class.

public class Register {
    private ArrayList<Hund> hundRegister;
    private Register(){
        hundRegister = new ArrayList<Hund>();
    }
}

Additionally, it's unclear why the constructor is private. Nothing else can access that constructor. I would make it public.

Also, in getSvanslängd, replace ras=="tax" with "tax".equals(ras). See How do I compare strings in Java?.

Community
  • 1
  • 1
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • Thanks! A moment of shame for me then ;) pretty obvious when i see the answer ;) – Oskar Dec 04 '14 at 19:54
  • 1
    Throwing me a NullpointerException, but no compilation errors now though. Im guessing i got some more troubleshooting to do xD – Oskar Dec 04 '14 at 20:05