简体   繁体   中英

Adding an object to an array in a separate class

edit: I am looking to pass HomeBuyers Objects to my homeBuyers ArrayList in my CreditUnion class. The this.homeBuyers.add function throws a "cannot find symbol" error. I have tried making the firstName, lastName, and creditScore vars static and passing the object in with HomeBuyers(HomeBuyers.firstName, HomeBuyers.lastName, HomeBuyers.creditScore). That avoided errors but did not add the object to the ArrayList.

public class LabProgram {

public static void main(String[] args) {

    CreditUnion cu = new CreditUnion();

    cu.addHomeBuyer(new HomeBuyers("first","last",600));

    }

}

  public class HomeBuyers {
    public String firstName;
    public String lastName;
    public int creditScore;

public HomeBuyers(String firstName, String lastName, int creditScore) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.creditScore = creditScore;
  }

  }

   public class CreditUnion {
     public ArrayList<HomeBuyers> homeBuyers;

public CreditUnion() {
    this.homeBuyers = new ArrayList<>();
      }


public void addHomeBuyer(HomeBuyers homeBuyers) {
     this.homeBuyers.add(HomeBuyers(firstName, lastName, creditScore));
}

You have multiple problems here.

The right syntax for creating a new object is new HomeBuyers(...) . Not HomeBuyers() .

Separately, firstName doesn't exist as a variable in your addHomeBuyer method. The only variable that does exist is homeBuyers . You could write homeBuyers.firstName . However, you already have an instance of your class HomeBuyers . There is no need to make another one with identical values. this.homeBuyers.add(homeBuyers) would have done the job.

These questions are incredibly simplistic; stack overflow probably isn't the right venue. I suggest any of the many nice tutorials out there, they tend to take a little more time to explain things in an orderly fashion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM