Len_X
Len_X

Reputation: 863

Java: Read text file and add to an Array

After reading a text file and printing it out like so:

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

Print:

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

With this data, how do I calculate:

Oldest Person 
Youngest Person

And print it out programmatically. New to Java.

Upvotes: 1

Views: 2585

Answers (2)

nbokmans
nbokmans

Reputation: 5747

As user Bradimus mentioned in the comments, this is perfect for using classes.

If you look at the data in your file they are all the "same" type - every line has a first name, surname, age, weight and height. You can bundle them into an object and make them easier to use in your code.

Example:

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

Then in your main class, you can just add them to an list like so. I added an example for how to calculate the oldest person, you can copy this logic (iterate over all the persons in the personList, perform check, return desired result) for the other tasks.

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

Upvotes: 2

Eritrean
Eritrean

Reputation: 16498

You have an ArrayList called "arrayOfPeople", which you do not use yet. While reading your file line by line store the data in your list "arrayOfPeople" and calculate the needed values.

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

Upvotes: 1

Related Questions