1

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.

4
  • Iterate over your ArrayList and tally these results, then divide by the size of the list to get averages. Commented Nov 21, 2016 at 13:46
  • 2
    You should create a Person object to hold your data. Commented Nov 21, 2016 at 13:48
  • @bradimus can you give a example of how to do this Commented Nov 21, 2016 at 14:01
  • The tutorial is a fine place to start. Commented Nov 21, 2016 at 14:13

2 Answers 2

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Personally, instead of passing a string through the constructor, I would create a public static method called parse(String) on the Person class. Input should be controlled when dealing with a constructor.
Yes that would be a better route to go normally but since this person is new to Java/OO I wanted to show what a constructor can do, and since the input is controlled (at least judging by his sample in OP) it wouldn't be too big of a problem. But this constructor definitely wouldn't work with any different format. Thanks for the edit.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.