如何构造未知数量的对象?

时间:2019-02-23 04:35:52

标签: java

我用于构建对象的代码是:

    public static void addAnimal() throws ParseException {


     Scanner in=new Scanner(System.in);

     System.out.printf("Enter animal name: ");
     String animalNameIn = in.nextLine();

     System.out.printf("Enter animal species: ");
     String animalSpeciesIn = in.nextLine();

     System.out.printf("Enter animal gender: ");
     String animalGenderIn = in.nextLine();

     System.out.printf("Enter animal birth date (year,month,day): ");
     LocalDate animalBirthDateIn = LocalDate.of(in.nextInt(), in.nextInt(), in.nextInt());

     System.out.printf("Enter if animal is on loan (true/false): ");
     boolean animalOnLoanIn = in.nextBoolean();

     Animal firstAnimal = new Animal(animalNameIn,animalSpeciesIn,animalGenderIn,animalBirthDateIn,animalOnLoanIn);

     System.out.println(firstAnimal.animalName);
     System.out.println(firstAnimal.animalSpecies);
     System.out.println(firstAnimal.animalGender);
     System.out.println(firstAnimal.animalBirthDate);
     System.out.println(firstAnimal.animalOnLoan);
}

需要重命名变量“ firstAnimal”时,我该怎么办?

1 个答案:

答案 0 :(得分:1)

您的问题尚不明确。据我了解,您应该尝试使用ArrayList做事。它使事情变得容易得多。 而且,您正在从用户那里获取输入,如果您想多次从用户那里获取输入,则应该使用循环,并在每次这样从用户那里获取输入时创建对象,

Animal animal=null; //remember, its your class name, that's why i used
ArrayList<Animal> animalList=new ArrayList<>(); //create array list to store object you created, so if you create object next time it wouldn't affect previous object   
for(int i=0; i<timesYouWantToTakeInputFromUser; i++){
   /*
   *code for taking input from user
   *like animalNameIn,animalSpeciesIn,animalGenderIn,animalBirthDateIn,animalOnLoanIn
*/
animal=new Animal(animalNameIn,animalSpeciesIn,animalGenderIn,animalBirthDateIn,animalOnLoanIn);
animalList.add(animal);
}

之后,您可以通过以下方式访问此信息

for(Animal animals:animalList){
 animals.animalNameIn //or whatever your variable name is
 animals.animalSpeciesIn //and so on
}

这对您来说很好。如果您需要其他东西,则应澄清您的问题