有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用扫描仪读取文件数据

我正在研究的方法是readDataFromFile()。它读取数据以Tabs分隔的文件,例如:

Bird    Golden Eagle    Eddie
Mammal  Tiger   Tommy
Mammal  Lion    Leo
Bird    Parrot  Polly
Reptile Cobra   Colin

这是我一直被要求做的,但我可能不完全理解如何创建这个,任何帮助将不胜感激

向我提出的问题是:

Spaces at the beginning or end of the line should be ignored. You should extract the three substrings and then create and add an Animal object to the zoo. You should ignore the first substring ("Bird" in the above example) as it is not required for this part of this project. Also note that, similar to the code you should have commented out, the addAnimal() method will require a third parameter "this" representing the owner of the collection. On successful completion of this step you will have a "basic" working version of readDataFromFile()

动物园类:

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 String allocateId()
   {
      nextAnimalIdNumber++;
      String s = Integer.toString(nextAnimalIdNumber);
      while ( s.length()<6 )
         s = "0" + s;
      return zooId + "_" +  s;
   }

   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);
      //System.out.println("The selected file is " + fileName);

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

动物类别:

public class Animal
{
   private String id;
   private String species;
   private String name;
   public Animal(String species, String name, MyZoo owner)
   {
      id = owner.allocateId();
      this.species = species;
      this.name  = name;
   }

   public String getId()
   {
      return id;
   }

   public String getName()
   {
      return name;
   }

   public String getSpecies()
   {
      return species;
   }

   public String toString()
   {
      return id + "  " + name + ": a " + species;
   }
}

共 (2) 个答案

  1. # 1 楼答案

    您可以简单地使用^{}来读取您的文件(这里我使用了一个String来匹配您在文件中可以找到的内容)

    Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern

    String data = "Bird\tGolden    Eagle \t Eddie\nMammal \t Tiger  Tommy";
    Scanner scanner = new Scanner(data);
    
    while (scanner.hasNext()) {
        System.out.println("Animal: " + scanner.next());
    }
    scanner.close();
    

    输出:

    Animal: Bird
    Animal: Golden
    Animal: Eagle
    Animal: Eddie
    Animal: Mammal
    Animal: Tiger
    Animal: Tommy
    

    这将使用类中定义的来自Scanner的分隔符

    A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace

    我们可以使用

    System.out.println(scanner.delimiter());
    

    \p{javaWhitespace}+

  2. # 2 楼答案

    while( scanner.hasNext() ) {
        String fileLine = scanner.nextLine()
        String[] animalNames = fileLine.split("\t")
        ...
    }
    

    您已经在代码中使用了扫描器,因此我假设您大致了解扫描器的工作原理。上面的代码首先以字符串形式读入下一行输入。例如,在第一位之后

    fileLine := "Bird    Golden Eagle    Eddie"
    

    然后,我声明了一个名为animalNames的字符串数组,并将其设置为fileLine.split("\t")。这是一个可以在字符串上调用的方法-它所做的是返回一个由子字符串组成的数组,由您给它的任何内容分隔。在本例中,我给出了函数"\t",它是表示选项卡的字符。那么在这一行之后,

    animalNames := {"Bird", "Golden Eagle", "Eddie"}
    

    由于您现在有了一个字符串数组,您可以通过从中选取项目来完成剩余的赋值-例如

    animalNames[0] := "Bird"
    animalNames[1] := "Golden Eagle"
    animalNames[2] := "Eddie"