java - 在Java中对两个相同名称的文本文件进行排序

标签 java

我目前正在开发一个 Java 项目,

以下是我迄今为止的编码尝试:

     public class MyZoo
{
   // zoo identifier
   private String zooId;
   // a number used in generating a unique identifier for the next animal to be added to the zoo
   private int nextAnimalIdNumber;
   // zstorage for the Animal objects
   private TreeMap<String, List<Animal>> animals;

   /**
    * Create an "empty" zoo.
    *
    * @param zooId an identifier for the zoo, at least three characters long.
    */
   public MyZoo(String zooId)
   {
      this.zooId = zooId.trim().substring(0,3).toUpperCase();
      nextAnimalIdNumber = 0;
      animals = new TreeMap<String, List<Animal>>();
   }

   /**
    * Returns a unique identifier, for an <tt>Animal</tt> object, based on the
    * zoo identifier and the field <tt>nextAnimalIdNumber</tt> which is incremented
    * ready for next time the method is called.
    *
    * @return a unique identifier.
    */
   public String allocateId()
   {
      // increment nextAnimalIdNumber and then construct a six digit string from it
      nextAnimalIdNumber++;
      String s = Integer.toString(nextAnimalIdNumber);
      while ( s.length()<6 )
        s = "0" + s;
      return zooId + "_" +  s;
   }

   /**
    * Adds an animal to the zoo.
    *
    * @param animal the Animal object to be added.
    */
   public void addAnimal(Animal animal)
   {
    String animalName = animal.getName();
    // Is there already an animal with the same name?
    if (!animals.containsKey(animalName)){
        // If it is not in the map, create a list
        animals.put(animalName, new ArrayList<Animal>());
    }
    // Now add the animal to the list
    animals.get(animalName).add(animal);
}

   /**
    * Reads <tt>Animal</tt> data from a text file and adds them to the zoo.  The
    * format of the data is specified in the MyZoo coursework assignment.
    *
    * @param animal the Animal object to be added.
    */
   public void readDataFromFile()
   {
      int noOfAnimalsRead = 0;

      // set up an owner for the FileDialog
      JFrame jframe = new JFrame();
      jframe.setVisible(true);
      // use a Filedialog to select a file to read from
      FileDialog fDialog = new FileDialog(jframe, "Read from", FileDialog.LOAD);
      fDialog.setFile("import001.txt");
      fDialog.setDirectory(".");
      fDialog.setVisible(true);
      String fname = fDialog.getFile();
      jframe.dispose();

       File inFile = new File(fname);

    String fileName = "import002.txt";

        // This will reference one line at a time
        String line = null;


        try {
            // FileReader reads text files in the default encoding.
            FileReader fileReader = 
                new FileReader(fileName);

            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = 
                new BufferedReader(fileReader);

            while((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }   

            // Always close files.
            bufferedReader.close();         
        }
        catch(FileNotFoundException ex) {
            System.out.println(
                "Unable to open file '" + 
                fileName + "'");                
        }
        catch(IOException ex) {
            System.out.println(
                "Error reading file '" 
                + fileName + "'");                  

        }

      addAnimal( new Animal("golden eagle", "Eddie", this) );               //
      addAnimal( new Animal("tiger", "Tommy", this) );            
      addAnimal( new Animal("lion", "Leo", this) );         
      addAnimal( new Animal("parrot", "Polly", this) );             
      addAnimal( new Animal("cobra", "Collin", this) );       

      noOfAnimalsRead = 5;                                       

      // this next line should be retained
      System.out.println("no of animals read from file was " + noOfAnimalsRead + "\n");
   }

   /**
    * Prints out details of all animal in the zoo.
    *
    */
   public void printAllAnimals()
   {

      System.out.println("\nDetails for all animals in Zoo " + zooId);
      System.out.println(  "==================================");

      Collection<Animal> c = animals.values();
    // The name of the file to open.
        String fileName = "import001.txt";

        // This will reference one line at a time
        String line = null;
for (Map.Entry<String, List<Animal>> animalEntry : animals.entrySet())
{
    List<Animal> animalsOfAName = animalEntry.getValue();
    for (Animal animal: animalsOfAName){
        // output here, change as appropriate, maybe add the type of animal
        System.out.println(animal.getName());
    }
}
        }
    }

但是文本文件(Eddie)中有相同的文本名称,如何让第二个Eddie替换第一个Eddie而不丢失字母顺序,在addAnimal()中put()使用名称字段

最佳答案

键在 map 中必须是唯一的,这就是第二个艾迪动物取代第一个的原因。

要在同一个键下保存多个对象,您可以声明一个 Map,它使用 List(或其他适当的 Collection)作为键值对中的值.

TreeMap<String, List<Animal>> animals;

现在添加动物时需要一些逻辑来处理这个问题。

public void addAnimal(Animal animal)
{
    String animalName = animal.getName();
    // Is there already an animal with the same name?
    if (!animals.containsKey(animalName){
        // If it is not in the map, create a list
        animals.put(animalName, new ArrayList<Animal>();
    }
    // Now add the animal to the list
    animals.get(animalName).add(animal);
}

现在要打印,您需要遍历每个名​​称的动物:

for (Map.Entry<String, List<Animal>> animalEntry : animals.entrySet())
{
    List<Animal> animalsOfAName = animalEntry.getValue();
    for (Animal animal: animalsOfAName){
        // output here, change as appropriate, maybe add the type of animal
        System.out.println(animal.getName());
    }
}

关于java - 在Java中对两个相同名称的文本文件进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25168549/

相关文章:

java - Android RelativeLayout 拉伸(stretch)背景

java - 保存当前日期

java - 如何从另一个类更新JLabel的?

java : String to JSON order changed

java - 删除父元素而不删除子元素 DOM

java - Maven-Surefire-Report 插件未生成报告

java - 动态控制@Formula 列的惰性/急切加载

java - android数据库的交换id

java - 这段代码是适配器模式的示例吗?

java - 运算符 reinterpret_cast<const uint8_t*> 后出现错误 "core dumped"