简体   繁体   中英

How do I load data file into an arraylist

I need help creating a method that loads pets. I am having difficulty writing a while loop that reads the file pets.txt and stores it in an array list and returns the total number of pets. Once I have the pets loaded I need to create a method to print the list, a method to find the heaviest pet and a method to find the average weight of the pets.

Here is what I have so far:

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 looks like this:

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

The format of this information is

(name of pet, name of owner, weight, breed)

In your loop you iterate over every line of the file. So you have to parse the line in it´s content (Split) and then save the informations in

Second you should create an Pet-Object (Objects and Classes) and save the information in each object. Your arraylist contains the created objects.

If you got some specific code, maybe someone will give you a more specific help.

What you have done so far is too "load" the file. You must now use the inFile (the scanner object) to access the contents of the pets.txt. This can be done in many ways such as using inFile.nextLine() (see the Javadocs).

Thereafter use string methods such as split() (again see the docs) to extract whichever parts of the string you want in the necessary format, to store in a Pets class.

You should then store each Pets object in a data structure (eg list) to enable you to write the methods you need in an efficient manner.

Pet Class

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
}

File reading method

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);
    }
}

First of all I would not read the data into a simple array list. I would probably use an ArrayList of classes. So I would declare a second class something like this:

//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;
   }

}

Then back in whatever your main class is I would make the following method:

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;
}

Solution

This is my solution to this problem with the methods that you mentioned that you wanted. I simply just create a pet class and create an arraylist of the pet object and add the pet objects to the list when I use the scanner to get the data from the file!

Pet Class

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;
}
}

Main Class

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

Please make sure that between every item there is a command and space like this ", " that is so we know when the next item is.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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