我正在为学校编写程序,必须将来自不同班级的两个不同对象相关联。但是,我希望用户在使用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();
}
}
}
答案 0 :(得分:0)
首先,我认为您想将狗分配给所有者,而不是所有者。
狗的主人在哪里?在所有者的班级中创建一个列表,然后在创建狗之后,将其添加到该列表中。
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);
}