Как назначить объект другому объекту с помощью сканера - PullRequest
0 голосов
/ 26 января 2019

Я пишу программу для школы, в которой мне нужно связать два разных предмета из разных классов. Однако я хочу, чтобы пользователь назначил существующий объект-владелец собаке, пока пользователь создает новый объект собаки с помощью сканера. У меня есть два отдельных класса (один для собак и один для владельцев) и тестер 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();

        }
    }
}

1 Ответ

0 голосов
/ 26 января 2019

Прежде всего, я думаю, что вы хотите назначить собаку владельцу, а не владельцу собаки.

Где владелец собаки?Создайте список в классе владельца и после создания собаки добавьте его в этот список.

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();

    }
}
}

Эта функция должна быть в классе владельца.

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