Java:读取文本文件并添加到Array

时间:2016-11-21 13:42:52

标签: java csv

阅读文本文件后将其打印出来:

public static void main(String[] args) {

    File file = new File("/Users/Len/Desktop/TextReader/src/example.txt");
    ArrayList<String[]> arrayOfPeople = new ArrayList<>();

    try {

        Scanner input = new Scanner(file);
        while (input.hasNext()) {

        String num = input.nextLine();
        System.out.println(num);

        }
    } catch (FileNotFoundException e) {
        System.err.format("File Does Not Exist\n");
    }
}

打印:

First Name, Surname, Age, Weight, Height
First Name, Surname, Age, Weight, Height

有了这些数据,我该如何计算:

Oldest Person 
Youngest Person

以编程方式打印出来。 Java新手。

2 个答案:

答案 0 :(得分:2)

正如用户Bradimus在评论中提到的,这非常适合使用类。

如果你查看文件中的数据,他们就是&#34;相同的&#34; type - 每行都有名字,姓氏,年龄,体重和身高。您可以将它们捆绑到一个对象中,并使它们更容易在代码中使用。

示例:

public class Person {
    public String firstName;
    public String surname;
    public int age;
    public int height;
    public int weight;

    public Person(String input) {
        //You can parse the input here. One 'input' is for example "Gordon, Byron, 37, 82, 178"
        String[] splitString = input.split(", ");
        this.firstName = splitString[0];
        this.surname = splitString[1];
        this.age = Integer.parseInt(splitString[2]);
        this.height = Integer.parseInt(splitString[3]);
        this.weight = Integer.parseInt(splitString[4]);
    }
}

然后在您的主类中,您可以将它们添加到列表中。我添加了一个如何计算最老的人的例子,你可以复制这个逻辑(迭代personList中的所有人,执行检查,返回所需的结果)。

// Other code
public static void main(String[] args) {
    List<People> peopleList = new ArrayList<>();
    File file = new File("/Users/Len/Desktop/TextReader/src/example.txt");
    try {
        Scanner input = new Scanner(file);
        while (input.hasNext()) {
        String num = input.nextLine();
        System.out.println(num);
        peopleList.add(new Person(num));
    } catch (FileNotFoundException e) {
        System.err.format("File Does Not Exist\n");
    }
    Person oldestPerson = getOldestPerson(peopleList);
    System.out.println("Oldest person: " + oldestPerson.firstName + " " + oldestPerson.surname);
}
public static Person getOldestPerson(List<Person> people) {
    Person oldestPerson = null;
    for (Person person: people) {
        if (oldestPerson == null || person.age > oldestPerson.age) {
            oldestPerson = person;
        }
    }
    return oldestPerson;
}

答案 1 :(得分:1)

您有一个名为“arrayOfPeople”的ArrayList,您还没有使用它。逐行读取文件时,会将数据存储在列表“arrayOfPeople”中并计算所需的值。

public static void main(String[] args) {
    File file = new File("c:/Users/manna/desktop/example.txt");
    ArrayList<String[]> arrayOfPeople = new ArrayList<>();

    try {
        Scanner input = new Scanner(file);
        input.nextLine();                         //do this to skip the first line (header)
        while (input.hasNext()) {
            String num = input.nextLine(); 
            String[] personData = num.split(","); //returns the array of strings computed by splitting this string around matches of the given delimiter
            arrayOfPeople.add(personData);
        }

        int oldest   = Integer.parseInt(arrayOfPeople.get(0)[2].trim()); //Integer.parseInt("someString") parses the string argument as a signed decimal integer.
        int youngest = Integer.parseInt(arrayOfPeople.get(0)[2].trim()); //String.trim() returns a copy of the string, with leading and trailing whitespace omitted
        double totalWeight = 0;
        double totalHeight = 0;
        double totalAge    = 0;

        for(int i = 0; i< arrayOfPeople.size(); i++){
            String[] personData = arrayOfPeople.get(i);
            if(Integer.parseInt(personData[2].trim())>oldest){
                oldest = Integer.parseInt(personData[2].trim());
            }
            if(Integer.parseInt(personData[2].trim())< youngest){
                youngest = Integer.parseInt(personData[2].trim());
            }

            totalWeight = totalWeight + Double.parseDouble(personData[3].trim());
            totalHeight = totalHeight + Double.parseDouble(personData[4].trim());
            totalAge = totalAge + Double.parseDouble(personData[2].trim());
        }

        System.out.println("Oldest Person: " + oldest);
        System.out.println("Youngest  Person: " + youngest);
        System.out.println("Average Weight: " + totalWeight/arrayOfPeople.size());
        System.out.println("Average Height: " + totalHeight/arrayOfPeople.size());
        System.out.println("Average Age: " + totalAge/arrayOfPeople.size());

    } catch (FileNotFoundException e) {
        System.err.format("File Does Not Exist\n");
    }
}