繁体   English   中英

Java Iterate Over Collection,无法按预期工作

[英]Java Iterate Over Collection ,not working as expected

我目前正在从事Java项目,到目前为止,我尝试进行以下编码:

import java.util.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Collection;
import java.util.Map;

/**
 *
 * This class models a zoo. It allows a single animal to be added to the zoo, a
 * batch of animals to be "imported" by reading data from a text file and for all
 * the animals to be listed in a terminal window.  It also ensures that all animals
 * in the zoo have a unique identifier.
 *


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, 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, 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)
   {
      animals.put(animal.getName(), 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;

        TreeMap sortedItems = new TreeMap(animals);

   // keySet returns the Map's keys, which will be sorted because it's a treemap.
   for(Object s: animals.keySet()) {

       // Yeah, I hate this too.
       String k = (String) s;

       // but now we have the key to the map.

       // Now you can get the AnimalItems.  
       List<Animal> listOfanimals = animals.get(s);

       // Iterate over this list for the associated animals
       for(AnimalItem animalItem: listOfAnimalanimals) {
          System.out.println(animalItem.getSomething());
          }
       }                                         
   }
}

我目前无法使printAllAnimals()方法正常工作。

当执行方法printAllAnimals()时,当应该使用Collection对象c时,它不执行任何操作,因此可以轻松地检查存储在动物园中的动物

我感到困惑,将不胜感激任何帮助。

这是什么?

List<Animal> listOfanimals = animals.get(s); // list is listOfanimals

// Iterate over this list for the associated animals
for(AnimalItem animalItem: listOfAnimalanimals) { // what is listOfAnimalanimals?
      System.out.println(animalItem.getSomething());
   }
}   

改成

for(AnimalItem animalItem: listOfanimals) { 
      System.out.println(animalItem.getSomething());
   }
} 

请使用调试器,这种问题您可以自己解决。

暂无
暂无

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

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