简体   繁体   English

OOP-Java。 从主将Animal对象添加到Class中的Arraylist中

[英]OOP-Java. Adding Animal objects to an Arraylist in the Class from the main

Adding a second Animal, resets the animals Arraylist to index 0. So it holds the last entered animal. 添加第二个动物,将动物Arraylist重置为索引0。因此,它将保留最后输入的动物。 I also putted the UML design below, so it might be more understandable what I'm trying. 我还将UML设计放在下面,所以我正在尝试的内容可能更容易理解。

public class Cage {
    private int placeNr;
    private ArrayList<Animal> animals = new ArrayList<Animal>();

    public Cage(int place) {
        this.placeNr = place;
    }

    public int getCageNr() {
        return this.placeNr;
    }


    public void putAnimal(Animal animal) throws DuplicateNameException {
        if(!duplicatedAnimal(animal.getName())) {
            animals.add(animal);
        }
    }
}

At this point I'm confused. 在这一点上我很困惑。 How do I add an Animal class in the an Arraylist located in Cage and stack my Animals in it. 如何在笼中的Arraylist中添加Animal类并将其Animals堆叠在其中。

private static void addAnimal() {
    Animal newAnimal;
    Cage cage;
    try {
        System.out.println("Name: ");
        String name = sc.next();
        System.out.println("Type: ");
        String type = sc.next();
        System.out.println("birthYear: ");
        int birthYear = sc.nextInt();
        System.out.println("Cage number: ");
        int cageNumber = sc.nextInt();

        cage = new Cage(cageNumber);
        newAnimal = new Animal(name, type, birthYear);
        cage.putAnimal(newAnimal);
    } catch (DuplicateNameException dne) {
        dne.getMessage();
    } catch (InputMismatchException ime) {
        System.out.println("Wrong input");
    }
}

If someone can push me in the right direction it will be awesome thanks! 如果有人可以向正确的方向推动我,那将非常感谢!

UML: enter image description here UML: 在此处输入图片描述

Every time you call addAnimal you will create a new Cage object and add the new animal to that cage. 每次调用addAnimal时,都会创建一个新的Cage对象,并将新的动物添加到该笼中。 To add several animals to the same cage the addAnimal method can not be static and cage needs to be a member of some class (AnimalKeeper?) 要将多个动物添加到同一笼中,addAnimal方法不能是静态的,并且笼必须是某个类的成员(AnimalKeeper?)

Something like this 像这样

public class AnimalKeeper {
  private Cage cage;

  public Cage getCage() {
      return cage;
  }

  public addAnimalToCage(Animal animal) {
      //the same method as above minus the user input
      //which needs to be done somewhere else
  }
}

I tried my best to figure out what you meant exactly, refactor your code to smth like this 我尽力弄清楚您的意思,将代码重构为这样

class DuplicateNameException extends Exception {

    private String message;

    public DuplicateNameException(String message){
        this.message = message;
    }

    public String getMessage(){
        return this.message;
    }

}

class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}


class Cage {
    private int placeNr;

    private ArrayList<Animal> animals = new ArrayList<Animal>();

    public Cage(int place) {
        this.placeNr = place;
    }

    public int getCageNr() {
        return this.placeNr;
    }


    public void putAnimal(Animal animal) throws DuplicateNameException {
        if(!duplicatedAnimal(animal.getName())) {
            animals.add(animal);
        } else {
            throw new DuplicateNameException(animal.getName());
        }
    }

    private boolean duplicatedAnimal(String name) {
        for (Animal animal : animals)
            if (animal.getName().equals(name))
                return true;

        return false;
    }

    public static void main(String[] args) {
        Animal newAnimal;
        Cage cage;
        try {
            cage = new Cage(1);
            newAnimal = new Animal("Dog");
            cage.putAnimal(newAnimal);
            cage.putAnimal(new Animal("not dog"));
            cage.putAnimal(new Animal("Dog"));
        } catch (DuplicateNameException dne) {
            System.out.println(dne.getMessage());
        }
    }
} 

Note: with this code you need to consider cases with animals name written in lower case and upper case ( equals will return false in this case) use toLowerCase() or toUpperCase() to normelize the name to common ground 注意:使用此代码,您需要考虑大小写动物名称的情况,小写字母和大写字母(在这种情况下, equals将返回false )使用toLowerCase()toUpperCase()将名称归一化

another option you can take is to use HashMap object, this structure type has duplication elimination build in, you will have to override the hashCode() function of Animal so the map will know how to hash each object, like 您可以采取的另一种选择是使用HashMap对象,该结构类型具有消除重复的功能,您将必须覆盖AnimalhashCode()函数,以便map知道如何对每个对象进行哈希处理,例如

@Override
public int hashCode() {
  return this.name.hashCode()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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