提取3个子字符串并创建Animal对象

时间:2018-07-12 14:16:00

标签: java

我目前正在使用“ readDataFromFile() ”方法,该方法读取文本文件,例如:

Bird    Golden Eagle    Eddie
Mammal  Tiger   Tommy
Mammal  Lion    Leo
Bird    Parrot  Polly
Reptile Cobra   Colin
  • 如何提取 3 substrings ,然后创建 Animal object 并将其添加到 {{1 }}

  • 动物对象具有:名称和种类。

我有2个班级:Zoo。在这个问题上的任何帮助都将是惊人的。

动物园类:

Zoo and Animal

动物类:

public class MyZoo
{
   private String zooId;
   private int nextAnimalIdNumber;
   private TreeMap<String, Animal> animals;
   private Animal animal;

   public MyZoo(String zooId)
   {
      this.zooId = zooId.trim().substring(0,3).toUpperCase();
      nextAnimalIdNumber = 0;
      animals = new TreeMap<String, Animal>();
   }

   public void addAnimal(Animal animal)
   {
      animals.put(animal.getName(), animal);
      this.animal = animal;
   }

   public void readDataFromFile() throws FileNotFoundException
   {
      int noOfAnimalsRead = 0;

      String fileName = null;

      JFrame mainWindow = new JFrame();
      FileDialog fileDialogBox = new FileDialog(mainWindow, "Open", FileDialog.LOAD);
      fileDialogBox.setDirectory("."); 
      fileDialogBox.setVisible(true);

      fileName = fileDialogBox.getFile();
      String directoryPath = fileDialogBox.getDirectory();

      File dataFile = new File (fileName);
      Scanner scanner = new Scanner(dataFile);

      scanner.next();
      while(scanner.hasNext())
       {
       String name = scanner.nextLine();
       System.out.println("Animal: " + name);
       }

      scanner.close();
   }

1 个答案:

答案 0 :(得分:2)

将输入拆分为行,然后将每行拆分为字段。两者都可以使用String.split完成。

String input = "Bird\tGolden Eagle\tEddie\n"
        + "Mammal\tTiger\tTommy\n"
        + "Mammal\tLion\tLeo\n"
        + "Bird\tParrot\tPolly\n"
        + "Reptile\tCobra\tColin";

MyZoo zoo = new MyZoo();

for (String line : input.split("\n")) {
    String[] parts = line.split("\t");
    Animal animal = new Animal(parts[1], parts[2], zoo);
    System.out.println(animal);
}

输出:

some-random-id  Eddie: a Golden Eagle
some-random-id  Tommy: a Tiger
some-random-id  Leo: a Lion
some-random-id  Polly: a Parrot
some-random-id  Colin: a Cobra