簡體   English   中英

如何將數據文件加載到arraylist中

[英]How do I load data file into an arraylist

我需要幫助來創建一種加載寵物的方法。 我在編寫while循環時遇到困難,該循環讀取文件pets.txt並將其存儲在數組列表中並返回pet的總數。 裝入寵物后,我需要創建一種方法來打印列表,找到最重的寵物的方法以及找到寵物的平均體重的方法。

這是我到目前為止的內容:

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

該信息的格式為

(寵物名稱,主人名稱,體重,品種)

在循環中,您遍歷文件的每一行。 因此,您必須解析其內容(拆分)中的行 ,然后將信息保存到

其次,您應該創建一個Pet對象(對象和類)並將信息保存在每個對象中。 您的arraylist包含創建的對象。

如果您有一些特定的代碼,也許有人會給您更具體的幫助。

到目前為止,您所做的也是“加載”文件。 現在,您必須使用inFile(掃描程序對象)來訪問pets.txt的內容。 這可以通過許多方式完成,例如使用inFile.nextLine()(請參閱Javadocs)。

之后,使用字符串方法(例如split()(再次參見文檔))以所需的格式提取所需的字符串的任何部分,以存儲在Pets類中。

然后,您應該將每個Pets對象存儲在一個數據結構(例如列表)中,以使您能夠高效地編寫所需的方法。

寵物課

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

首先,我不會將數據讀取到簡單的數組列表中。 我可能會使用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;
}

這是我使用所需的方法解決此問題的方法。 我只是創建一個寵物類,創建一個寵物對象的數組列表,然后在使用掃描儀從文件中獲取數據時將寵物對象添加到列表中!

寵物課

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM