2017-08-08 62 views
0

我需要帮助创建加载宠物的方法。我有困难 写一个while循环读取文件pets.txt并将其存储在数组 列表中,并返回宠物总数。一旦我有宠物加载,我需要创建一个打印列表的方法,找到宠物最重的 和找到宠物平均体重的方法。如何将数据文件加载到数组列表中

这是我到目前为止有:

try { 
    inFile = new Scanner(new FileReader("pets.txt")); 
} catch (FileNotFoundException ex) { 
    System.out.println("File data.txt not found"); 
    System.exit(1); 
} 

int i = 0; 

while (inFile.hasNext() && i < list.length) { 
    // cant figure out how to write this 
    i++; 
} 

inFile.close(); 

return i; 

pets.txt看起来是这样的:

muffin, bobby, 25.0, pug 
tiny, seth, 22.0, poodle 
rex, david, 40.0, lab 
lucy, scott, 30.0, bulldog 

此信息的格式是

(宠物的名字,名称所有者,体重,品种)

+0

你检出了['Scanner' javadoc](https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html)吗?它很清楚如何使用它,并提供了很好的例子。 – Aaron

+4

您是否已经创建了一个拥有一个Pet值的Pet类?如果不是,这可能是你想要开始的第一件事。 –

+0

也可能没有必要维护一个'i'变量:你不需要它作为停止条件('inFile.hasNext()'足以检查你什么时候读完了所有的宠物),而且你可以最后返回数组的长度。 – Aaron

回答

0

解决方案

这是我用你提到的方法解决这个问题。我只需创建一个宠物类并创建宠物对象的数组列表,并在使用扫描仪从文件中获取数据时将宠物对象添加到列表中!

宠物类

public class Pet { 

//Fields Variables 
private String pet_name; 
private String owner_name; 
private double weight; 
private String breed; 

//Constructor 
public Pet (String name, String o_name, double weight, String breed) { 

    //Set the variable values 
    this.pet_name = name; 
    this.owner_name = o_name; 
    this.weight = weight; 
    this.breed = breed; 
} 

//Getter and setter 
public String getPet_name() { 
    return pet_name; 
} 

public void setPet_name(String pet_name) { 
    this.pet_name = pet_name; 
} 

public String getOwner_name() { 
    return owner_name; 
} 

public void setOwner_name(String owner_name) { 
    this.owner_name = owner_name; 
} 

public double getWeight() { 
    return weight; 
} 

public void setWeight(double weight) { 
    this.weight = weight; 
} 

public String getBreed() { 
    return breed; 
} 

public void setBreed(String breed) { 
    this.breed = breed; 
} 
} 

主类

public class Main { 

//ArrayList 
private static ArrayList<Pet> pets = new ArrayList<>(); 

public static void main (String [] args) { 

    try { 
     Scanner sc = new Scanner(new File("path/to/file.txt")).useDelimiter(", |\n"); 

     while (sc.hasNext()) { 

      //Get the info for the pet 
      Pet pet; 

      String name = sc.next(); 
      String owner_name = sc.next(); 
      double weight = sc.nextDouble(); 
      String breed = sc.next(); 

      //Create the pet and add it to the array list 
      pet = new Pet (name, owner_name, weight, breed); 
      pets.add(pet); 

     } 

     sc.close(); 

    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 

    //Add your custom pets here if you would like! 
    addNewPet ("muffy", "john", 30.0, "beagle"); 

    //Custom Methods 
    printList(); 
    findHeaviestPet(); 
    findLightestPet(); 
    getAveragePetWeight(); 

} 

public static void printList() { 

    for (int i = 0; i < pets.size(); i++) { 
     System.out.println (pets.get(i).getPet_name()+" "+pets.get(i).getOwner_name() 
       +" "+pets.get(i).getWeight()+" "+pets.get(i).getBreed()); 
    } 

} 

public static void findLightestPet() { 
    //So we know the value will be assigned on the first pet 
    double weight = Double.MAX_VALUE; 
    int petIndex = 0; 

    for (int i = 0; i < pets.size(); i++) { 

     if (pets.get(i).getWeight() < weight) { 
      weight = pets.get(i).getWeight(); 
      petIndex = i; 
     } 
    } 

    System.out.println("The lightest pet is "+pets.get(petIndex).getPet_name()+", with a weight of "+pets.get(petIndex).getWeight()); 
} 

public static void findHeaviestPet() { 
    double weight = 0.0; 
    int petIndex = 0; 

    for (int i = 0; i < pets.size(); i++) { 

     if (pets.get(i).getWeight() > weight) { 
      weight = pets.get(i).getWeight(); 
      petIndex = i; 
     } 
    } 

    System.out.println("The heaviest pet is "+pets.get(petIndex).getPet_name()+", with a weight of "+pets.get(petIndex).getWeight()); 
} 

public static void getAveragePetWeight() { 
    double weights = 0; 

    for (int i = 0; i < pets.size(); i++) { 

     weights += pets.get(i).getWeight(); 
    } 

    weights = (weights/pets.size()); 

    System.out.println ("The average weight is "+weights); 
} 

public static void addNewPet (String name, String o_name, double weight, String breed) { 
    Pet pet = new Pet(name, o_name, weight, breed); 
    pets.add(pet); 
} 

} 

Pets.txt

请确保每一个项目之间有一个命令和空间像这样“,”这就是我们知道下一次迭代的时间米是。

muffin, bobby, 25.0, pug 
tiny, seth, 22.0, poodle 
rex, david, 40.0, lab 
lucy, scott, 30.0, bulldog 
name, owner_name, 65.0, breed 
+0

@cruiser你可以将它添加到你的文件文件!在最后或任何你想要的地方,只要宠物遵循所有其他宠物的创建方式!或者按照这种方式创建它!检查答案! – cunniemm

+0

@cruiser你可以确保你使用的是与问题中使用的完全相同的数据吗?如果你检查了你的数据和它的好处,然后请回复。 – cunniemm

+0

@cruiser检查答案! – cunniemm

0

在循环中,您遍历文件的每一行。所以你必须解析它的内容(Split)然后保存信息

其次你应该创建一个Pet-Object (Objects and Classes)并保存每个对象的信息。您的数据列表包含创建的对象。

如果你有一些特定的代码,也许有人会给你一个更具体的帮助。

0

到目前为止你所做的是太“加载”文件。您现在必须使用inFile(扫描仪对象)来访问pets.txt的内容。这可以通过很多方式完成,例如使用inFile.nextLine()(请参阅Javadocs)。

此后使用字符串方法,如split()(再次参阅文档)以必要的格式提取所需字符串的任何部分,以存储在Pets类中。

然后,您应该将每个Pets对象存储在数据结构(例如列表)中,以使您能够以高效的方式编写所需的方法。

0

宠物类

Public class Pet { 

    Public Pet(String pet_name, String owner, float weight, String breed) { 
     this.pet_name = pet_name; 
     this.owner = owner; 
     this.weight = weight; 
     this.breed = breed; 
    } 

    String pet_name; 
    String owner; 
    float weight; 
    String breed; 

    //implements getters and setters here 
} 

文件的阅读方法

private void read_file() throws Exception { 

    Scanner scanner = new Scanner(new FileReader("filename.txt")); 

    List<Pet> list = new ArrayList<>(); 

    while (scanner.hasNextLine()) { 
     String[] data = scanner.nextLine().split(","); 
     Pet pet = new Pet(data[0], data[1], Float.valueOf(data[2]), data[3]); 
     list.add(pet); 
    } 
} 
0

首先,我不会将数据读入一个简单的数组列表。我可能会使用类的ArrayList。所以,我将宣布第二类是这样的:

//Declare pet class 
class Pet{ 
    // Can be either public or private depending on your needs. 
    public String petName; 
    public String ownerName; 
    public double weight; 
    public String breed; 
    //Construct new pet object 
    Pet(String name, String owner, double theWeight, String theBreed){ 
     petName = name; 
     ownerName = owner; 
     weight = theWeight; 
     breed = theBreed; 
    } 

} 

然后回无论你的主类是我会做下面的方法:

public ArrayList<Pet> loadFile(String filePath){ 
    ArrayList<Pet> pets = new ArrayList<Pet>(); 
    File file = new File(filePath); 
    try { 
    Scanner sc = new Scanner(file); 
    while (sc.hasNextLine()) { 
     String s[] = sc.nextLine().split(","); 
     // Construct pet object making sure to convert weight to double. 
     Pet p = new Pet(s[0],s[1],Double.parseDouble(s[2]),s[3]); 
     pets.add(p);  
    } 
    sc.close(); 
    } 
    catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } 
    return pets; 
} 
相关问题