如何使用 Scanner 将一个对象分配给另一个对象

How to assign an object to another object using Scanner

我正在为学校编写程序,我必须将来自不同 类 的两个不同对象相关联。但是,我希望用户在使用 Scanner 创建新的 Dog 对象时将现有的 Owner 对象分配给 Dog。我有两个单独的 类(一个给 Dog,一个给 OWner)和一个测试器 Main.

public class DogOwnerTester {

    public static void main(String[] args) {

        List<Dog> dogList = new ArrayList<>();
        Scanner input = new Scanner(System.in);

        System.out.println("Would you like to add a dog? (Enter 'Y' or 'N')");
        String add = input.next();

        while (add.equalsIgnoreCase("y")) {
            System.out.println("Please enter the name of the dog: ");
            String name = input.next();
            System.out.println("Please enter the category of the dog: ");
            String category = input.next();
            System.out.println("Please enter the age of the dog: ");
            int age = input.nextInt();
            // System.out.println("Who is the dog's owner? ");
            // Somehow assign the owner to the dog using scanner?;

            Dog dog = new Dog(name, category, age, null);
            dogList.add(dog);

            System.out.println("Would you like to create another dog?(Enter 'Y' or 'N')");
            add = input.next();

        }
    }
}

首先,我认为您想将狗分配给主人,而不是将主人分配给狗。

狗的主人呢?在所有者的 class 中创建一个列表,并在创建狗后将其添加到该列表中。

public class DogOwnerTester {

     public static void main(String[] args) {

    List<Dog> dogList = new ArrayList<>(); // This list should be in user's class.
    Scanner input = new Scanner(System.in);

    //Create the owner object.
    Owner owner = new Owner(......); //Fill in the arguments



System.out.println("Would you like to add a dog? (Enter 'Y' or 'N')");
String add = input.next();

while (add.equalsIgnoreCase("y")) {
    System.out.println("Please enter the name of the dog: ");
    String name = input.next();
    System.out.println("Please enter the category of the dog: ");
    String category = input.next();
    System.out.println("Please enter the age of the dog: ");
    int age = input.nextInt();
    // System.out.println("Who is the dog's owner? ");
    // Somehow assign the owner to the dog using scanner?;

    Dog dog = new Dog(name, category, age, null);


    dogList.add(dog); // This should not be here.
    owner.addDogToList(dog);  //Call the owner's function to add the dog.

    System.out.println("Would you like to create another dog?(Enter 
            'Y' or 'N')");
    add = input.next();

    }
}
}

这个函数应该在所有者的 class.

public void addDogToList(Dog dog){
  this.dogList.add(dog);
}