2016-12-07 68 views
-3

我想创建一个包含文本文件信息的数组。如何在Java中创建文件内容的对象?

这是文件的样子:

ANIMAL   FEET  TAIL  DANGEROUS  COLOR 
Dog   4   Yes  No    Brown 
Spider   8   No   Yes   Black 
Snake   0   No   Yes   Green   

由制表符分隔。

我想创建一个对象的每个动物,脚的数量,尾巴和颜色作为属性。

任何人都可以帮助我吗?

+3

您需要首先发布您的代码。我们不会为你写信。 –

+0

请在您的问题中包含您尝试过的代码以及您的预期输出 – CraigR8806

回答

1

你还没有发布一个尝试,所以我不打算为你尝试,但只是一个你可以用在这样的问题中的提示是你可以创建一个类来表示这个信息。在你的问题中,你想要使用一个数组;这不是做事的最佳方式,而且您还用标记了您的问题。

首先,你可以读取一行行的文本文件,在每一个阶段,你可以创建一个Animal对象可以是这样:

class Animal { 

    private String name; 
    private int feet; 
    private boolean tail, dangerous; 
    private String color; 

    public Animal(){ 

    } 

    public Animal(String name, int feet, boolean tail, boolean dangerous, String color){ 
     this.name = name; 
     this.feet = feet; 
     this.tail = tail; 
     this.dangerous = dangerous; 
     this.color = color; 
    } 

    // getters and setters for these fields here 

} 

因为你是从这个文本文件的许多动物,你可能会发现按以下方式做一些事情很有用:

ArrayList<Animal> animals = new ArrayList<>(); 
for(each line of the textfile you read){ 
    animals.add(new Animal(...)); 
} 

这是数组可以提供帮助的部分。

相关问题