skip to Main Content

Title says all. I am currently working on a assignment for Object Oriented Programming. I do not understand how to properly add a specific field from a .tsv file. I am currently trying to add all ages together then find the average age.

I have been at this for sometime and thought it was time to ask for help.

Here is some example data from the tsv file:

8   I am a developer by profession  Yes 36  12  Yearly  116000  116000  United States   United States dollar    USD MongoDB MariaDB;MySQL;Redis "Developer, back-end;Developer, desktop or enterprise applications;Developer, game or graphics" "Bachelor’s degree (B.A., B.S., B.Eng., etc.)"  Employed full-time  White or of European descent    Man Remote work options;Opportunities for professional development;Family friendliness  Slightly dissatisfied   "I’m not actively looking, but I am open to new opportunities"  JavaScript  Python;SQL  Unity 3D    Ansible NA  "Confluence;Jira;Github;Slack;Microsoft Teams;Google Suite (Docs, Meet, etc)"   Yes Extremely important Not at all important/not necessary  Curious about other opportunities;Better compensation;Trouble with my direct manager;Trouble with leadership at my company;Better work/life balance;Wanting to work with new technologies;Growth or leadership opportunities    "Read company media, such as employee blogs or company culture videos;Company reviews from third party sites (e.g. Glassdoor, Blind);Personal network - friends or family;Read other media like news articles, founder profiles, etc. about the company"    Once a year Not sure    Yes No  Occasionally: 1-2 days per quarter but less than monthly    Start a free trial;Ask developers I know/work with;Visit developer communities like Stack Overflow;Read ratings or reviews on third party sites like G2Crowd    "Hello, old friend" Stack Overflow (public Q&A for anyone who codes);Stack Overflow Jobs (for job seekers)  Play games;Call a coworker or friend;Visit Stack Overflow;Go for a walk or other physical activity;Watch help / tutorial videos;Do other work and come back later   Linux-based 20 to 99 employees  iOS;Slack Apps and Integrations Docker  I have some influence   Straight / Heterosexual Yes "No, not really"    Less than once per month or monthly Multiple times per day  Easy    Appropriate in length   No  "Computer science, computer engineering, or software engineering"   Django;React.js;Vue.js  Flask   Just as welcome now as I felt last year 39  17  13
14  I am a developer by profession  Yes 27  13  Yearly  66000   66000   United States   United States dollar    USD Firebase;Microsoft SQL Server   Firebase;Microsoft SQL Server   "Developer, desktop or enterprise applications;Developer, front-end"    "Associate degree (A.A., A.S., etc.)"   Employed full-time  White or of European descent    Man Industry that I’d be working in;Flex time or a flexible schedule;Office environment or company culture  Slightly satisfied  "I’m not actively looking, but I am open to new opportunities"  HTML/CSS;JavaScript;SQL;TypeScript  HTML/CSS;JavaScript;SQL;TypeScript  Node.js Node.js "Confluence;Jira;Github;Microsoft Teams;Google Suite (Docs, Meet, etc)" Confluence;Jira;Github;Microsoft Teams  Yes Extremely important Somewhat important  Wanting to share accomplishments with a wider network;Curious about other opportunities;Better compensation;Wanting to work with new technologies;Growth or leadership opportunities    "Read company media, such as employee blogs or company culture videos;Company reviews from third party sites (e.g. Glassdoor, Blind);Publicly available financial information (e.g. Crunchbase);Read other media like news articles, founder profiles, etc. about the company"  Every few months    No  Yes No  Occasionally: 1-2 days per quarter but less than monthly    NA  Amused  Stack Overflow (public Q&A for anyone who codes);Stack Exchange (public Q&A for a variety of topics)    Call a coworker or friend;Visit Stack Overflow;Go for a walk or other physical activity;Do other work and come back later   Windows 100 to 499 employees    Google Cloud Platform;Raspberry Pi;Windows  Google Cloud Platform;Windows   I have little or no influence   Straight / Heterosexual Yes "Yes, definitely"   A few times per week    Multiple times per day  Neither easy nor difficult  Appropriate in length   No  "Computer science, computer engineering, or software engineering"   Angular;Vue.js  Angular;Vue.js  Just as welcome now as I felt last year 40  5   1
17  I am a developer by profession  Yes 25  14  Yearly  79000   79000   United States   United States dollar    USD Cassandra;Elasticsearch;MariaDB;PostgreSQL;Redis    Microsoft SQL Server;PostgreSQL "Developer, full-stack" "Bachelor’s degree (B.A., B.S., B.Eng., etc.)"  Employed full-time  White or of European descent    Man "Industry that I’d be working in;Languages, frameworks, and other technologies I’d be working with;Office environment or company culture"   Slightly dissatisfied   "I’m not actively looking, but I am open to new opportunities"  C#;Go;Haskell;HTML/CSS;JavaScript;Python;Ruby;Rust;SQL  C#;HTML/CSS;JavaScript;Python;SQL;VBA   .NET Core;Teraform  .NET;Node.js    "Github;Gitlab;Slack;Google Suite (Docs, Meet, etc)"    "Github;Gitlab;Slack;Microsoft Teams;Google Suite (Docs, Meet, etc)"    Yes Extremely important Fairly important    Having a bad day (or week or month) at work;Better compensation;Trouble with leadership at my company;Wanting to work with new technologies;Growth or leadership opportunities  "Company reviews from third party sites (e.g. Glassdoor, Blind);Personal network - friends or family;Read other media like news articles, founder profiles, etc. about the company;Directly asking current or past employees at the company"    Once a year Not sure    No  No  Rarely: 1-2 days per year or less   NA  "Hello, old friend" Stack Overflow (public Q&A for anyone who codes);Stack Exchange (public Q&A for a variety of topics);Stack Overflow Jobs (for job seekers)  Call a coworker or friend;Visit Stack Overflow;Do other work and come back later    Windows 20 to 99 employees  Docker;Kubernetes;Microsoft Azure   NA  I have little or no influence   Straight / Heterosexual Yes "No, not at all"    I have never participated in Q&A on Stack Overflow  Daily or almost daily   Easy    Appropriate in length   No  "Computer science, computer engineering, or software engineering"   ASP.NET Core;Gatsby;React.js;Vue.js ASP.NET;Gatsby;jQuery;React.js;Vue.js   Just as welcome now as I felt last year 40  7   3
18  I am a developer by profession  Yes 32  12  Monthly 105000  1260000 United States   United States dollar    USD Elasticsearch;PostgreSQL;Redis;SQLite   Elasticsearch;MariaDB;MySQL;Redis;SQLite    "Developer, back-end"   "Bachelor’s degree (B.A., B.S., B.Eng., etc.)"  Employed full-time  White or of European descent    Man "Languages, frameworks, and other technologies I’d be working with;Remote work options;Office environment or company culture"   Very satisfied  I am not interested in new job opportunities    HTML/CSS;Perl   Bash/Shell/PowerShell;HTML/CSS;Perl NA  NA  Github  Github;Slack    Not sure    Neutral Very important  Looking to relocate NA  Once every few years    Yes Onboarding? What onboarding?    Yes Occasionally: 1-2 days per quarter but less than monthly    Start a free trial;Ask developers I know/work with;Visit developer communities like Stack Overflow  "Hello, old friend" Stack Overflow (public Q&A for anyone who codes);Stack Exchange (public Q&A for a variety of topics)    Play games;Visit Stack Overflow;Do other work and come back later   Linux-based 100 to 499 employees    Linux   AWS;Linux   I have some influence   Straight / Heterosexual Yes "Yes, somewhat" I have never participated in Q&A on Stack Overflow  Daily or almost daily   Neither easy nor difficult  Appropriate in length   No  "Computer science, computer engineering, or software engineering"   NA  NA  Just as welcome now as I felt last year 45  19  12
19  I am a developer by profession  No  24  15  Yearly  83400   83400   United States   United States dollar    USD MariaDB;MongoDB MariaDB;Microsoft SQL Server    "Developer, full-stack" "Bachelor’s degree (B.A., B.S., B.Eng., etc.)"  Employed full-time  White or of European descent    Man Flex time or a flexible schedule;Office environment or company culture;Opportunities for professional development   Slightly dissatisfied   "I’m not actively looking, but I am open to new opportunities"  C#;Go;Python;TypeScript Bash/Shell/PowerShell;C#;HTML/CSS;JavaScript;SQL;TypeScript Node.js;React Native;Unity 3D;Unreal Engine .NET;.NET Core;Node.js  Github;Slack    Confluence;Jira;Github;Slack    Yes Extremely important Fairly important    Having a bad day (or week or month) at work;Trouble with my teammates;Growth or leadership opportunities    "Company reviews from third party sites (e.g. Glassdoor, Blind);Personal network - friends or family;Directly asking current or past employees at the company"  Once a year Yes No  No  Occasionally: 1-2 days per quarter but less than monthly    NA  "Hello, old friend" Stack Overflow (public Q&A for anyone who codes);Stack Exchange (public Q&A for a variety of topics);Stack Overflow Jobs (for job seekers)  Call a coworker or friend;Visit Stack Overflow;Go for a walk or other physical activity Windows "10,000 or more employees"  iOS;Slack Apps and Integrations Windows I have little or no influence   Straight / Heterosexual Yes Neutral Less than once per month or monthly A few times per week    Easy    Appropriate in length   No  "Computer science, computer engineering, or software engineering"   Django;Express;React.js Angular;Angular.js;ASP.NET Core Just as welcome now as I felt last year 35  9   3
41  I am a developer by profession  No  NA  15  Yearly  106000  106000  United States   United States dollar    USD Microsoft SQL Server    Microsoft SQL Server    "Developer, back-end;Developer, front-end;Developer, full-stack"    "Master’s degree (M.A., M.S., M.Eng., MBA, etc.)"   Employed full-time  NA  NA  Remote work options;Financial performance or funding status of the company or organization;Opportunities for professional development   Slightly dissatisfied   "I’m not actively looking, but I am open to new opportunities"  C;C#;Java;SQL   C;C#;Java;SQL   .NET;.NET Core;Node.js  .NET;Hadoop Microsoft Teams Slack;Microsoft Teams;Trello    No  Neutral Very important  Better compensation;Wanting to work with new technologies;Growth or leadership opportunities    "Read company media, such as employee blogs or company culture videos;Company reviews from third party sites (e.g. Glassdoor, Blind);Publicly available financial information (e.g. Crunchbase)"    Once a year No  No  No  Never   Start a free trial;Visit developer communities like Stack Overflow;Read ratings or reviews on third party sites like G2Crowd    "Hello, old friend" Stack Overflow (public Q&A for anyone who codes);Stack Exchange (public Q&A for a variety of topics)    Visit Stack Overflow;Do other work and come back later  Windows 500 to 999 employees    Windows Windows I have some influence   NA  Yes Neutral Daily or almost daily   Daily or almost daily   NA  NA  NA  "Computer science, computer engineering, or software engineering"   Vue.js  ASP.NET;Vue.js  A lot less welcome now than last year   40  25  20
42  I am a developer by profession  No  32  14  Yearly  130000  130000  United States   United States dollar    USD Cassandra;DynamoDB;MongoDB  Microsoft SQL Server;MySQL;Oracle;Redis "Developer, back-end;Developer, desktop or enterprise applications;Developer, front-end;Developer, full-stack;DevOps specialist"    "Bachelor’s degree (B.A., B.S., B.Eng., etc.)"  Employed full-time  White or of European descent    Man Remote work options;How widely used or impactful my work output would be;Office environment or company culture  Very satisfied  "I’m not actively looking, but I am open to new opportunities"  Bash/Shell/PowerShell;C#;Go;Java;Python;Rust    Bash/Shell/PowerShell;C#;HTML/CSS;Java;JavaScript;Python    .NET Core;Teraform  .NET;.NET Core;Node.js;Teraform Confluence;Jira;Gitlab  "Confluence;Jira;Github;Gitlab;Slack;Trello;Google Suite (Docs, Meet, etc)" Yes Somewhat important  Not at all important/not necessary  Curious about other opportunities;Better compensation;Trouble with leadership at my company;Better work/life balance;Wanting to work with new technologies;Growth or leadership opportunities   "Read company media, such as employee blogs or company culture videos;Company reviews from third party sites (e.g. Glassdoor, Blind);Personal network - friends or family"  Once every few years    Yes Yes Yes Rarely: 1-2 days per year or less   Start a free trial;Ask developers I know/work with;Visit developer communities like Stack Overflow  Amused  Stack Overflow (public Q&A for anyone who codes);Stack Exchange (public Q&A for a variety of topics);Stack Overflow Jobs (for job seekers)  Visit Stack Overflow;Go for a walk or other physical activity;Watch help / tutorial videos;Do other work and come back later    Windows "1,000 to 4,999 employees"  Android;AWS;Docker;Kubernetes;Raspberry Pi  AWS;Docker;Linux;MacOS;Raspberry Pi;Slack Apps and Integrations;Windows I have some influence   Straight / Heterosexual Yes "No, not really"    Less than once per month or monthly A few times per month or weekly Easy    Appropriate in length   No  "Computer science, computer engineering, or software engineering"   ASP.NET Core;Spring ASP.NET;Flask;React.js;Spring   Somewhat less welcome now than last year    37  16  10
43  I am a developer by profession  Yes NA  16  Yearly  135000  135000  United States   United States dollar    USD Oracle  Oracle  "Developer, back-end;Developer, front-end;Developer, full-stack"    "Master’s degree (M.A., M.S., M.Eng., MBA, etc.)"   Employed full-time  NA  NA  NA  Very dissatisfied   I am not interested in new job opportunities    Dart;HTML/CSS;Java;JavaScript;SQL   Dart;HTML/CSS;Java;JavaScript;SQL   Flutter Flutter Jira;Github Jira;Github Yes Extremely important Very important  NA  NA  Once a year No  Yes No  Sometimes: 1-2 days per month but less than weekly  Start a free trial;Visit developer communities like Stack Overflow;Research companies that have advertised on sites I visit Amused  Stack Overflow (public Q&A for anyone who codes)    Visit Stack Overflow;Watch help / tutorial videos   Windows "1,000 to 4,999 employees"  Linux   Linux   I have some influence   NA  Yes "Yes, definitely"   Daily or almost daily   Multiple times per day  Easy    Appropriate in length   NA  "Computer science, computer engineering, or software engineering"   NA  ASP.NET Just as welcome now as I felt last year 45  36  29
48  I am a developer by profession  No  38  30  Yearly  125000  125000  United States   United States dollar    USD PostgreSQL;Redis    PostgreSQL;Redis    "Developer, back-end"   "Bachelor’s degree (B.A., B.S., B.Eng., etc.)"  Employed full-time  White or of European descent    Man Flex time or a flexible schedule;Remote work options;Financial performance or funding status of the company or organization Slightly dissatisfied   I am actively looking for a job JavaScript;Ruby;SQL JavaScript;Ruby;SQL NA  NA  Github  "Confluence;Jira;Github;Slack;Google Suite (Docs, Meet, etc)"   Yes Extremely important Not at all important/not necessary  Better compensation;Better work/life balance    "Read company media, such as employee blogs or company culture videos;Company reviews from third party sites (e.g. Glassdoor, Blind)"   Once every few years    No  No  Yes Rarely: 1-2 days per year or less   NA  Indifferent Stack Overflow (public Q&A for anyone who codes);Stack Exchange (public Q&A for a variety of topics);Stack Overflow Jobs (for job seekers)  Visit Stack Overflow;Watch help / tutorial videos   MacOS   10 to 19 employees  AWS;Google Cloud Platform   AWS;Google Cloud Platform   I have a great deal of influence    Straight / Heterosexual Yes "Yes, definitely"   Daily or almost daily   Daily or almost daily   Easy    Appropriate in length   No  "Fine arts or performing arts (such as graphic design, music, studio art, etc.)"    Gatsby;Ruby on Rails    Gatsby;Ruby on Rails    NA  30  8   8
49  I am a developer by profession  No  23  15  Yearly  52000   52000   United States   United States dollar    USD Microsoft SQL Server    Microsoft SQL Server    "Developer, back-end;Developer, desktop or enterprise applications;Developer, front-end;Developer, full-stack"  "Bachelor’s degree (B.A., B.S., B.Eng., etc.)"  Employed full-time  White or of European descent    Man Industry that I’d be working in;Flex time or a flexible schedule;Remote work options    Very satisfied  "I’m not actively looking, but I am open to new opportunities"  C#;HTML/CSS;JavaScript;Python;TypeScript    C#;HTML/CSS;JavaScript;TypeScript   .NET;.NET Core  .NET;.NET Core  Microsoft Teams;Microsoft Azure Microsoft Teams;Microsoft Azure Yes Extremely important Somewhat important  Just because;Curious about other opportunities;Better compensation;Better work/life balance;Wanting to work with new technologies;Growth or leadership opportunities    "Read company media, such as employee blogs or company culture videos;Company reviews from third party sites (e.g. Glassdoor, Blind)"   Once every few years    Not sure    Onboarding? What onboarding?    No  Sometimes: 1-2 days per month but less than weekly  NA  Annoyed Stack Overflow (public Q&A for anyone who codes);Stack Exchange (public Q&A for a variety of topics)    Visit Stack Overflow;Do other work and come back later  Windows 100 to 499 employees    Microsoft Azure;Windows Microsoft Azure;Windows I have little or no influence   Straight / Heterosexual Yes Neutral Less than once per month or monthly Multiple times per day  Easy    Appropriate in length   No  "Computer science, computer engineering, or software engineering"   Angular;Angular.js;ASP.NET;ASP.NET Core ASP.NET;ASP.NET Core    Just as welcome now as I felt last year 40  8   4
53  I am a developer by profession  Yes 17  9   NA  NA  NA  United States   United States dollar    USD NA  SQLite  "Academic researcher;Developer, full-stack" "Secondary school (e.g. American high school, German Realschule or Gymnasium, etc.)"    "Independent contractor, freelancer, or self-employed"  East Asian  Man "Flex time or a flexible schedule;Languages, frameworks, and other technologies I’d be working with;How widely used or impactful my work output would be"   Slightly satisfied  "I’m not actively looking, but I am open to new opportunities"  Kotlin  Dart;HTML/CSS;Python    NA  Pandas;TensorFlow   NA  Github;Trello   NA  NA  Somewhat important  Just because;Better compensation;Trouble with leadership at my company;Looking to relocate  "Read company media, such as employee blogs or company culture videos;Company reviews from third party sites (e.g. Glassdoor, Blind);Publicly available financial information (e.g. Crunchbase);Personal network - friends or family"   Once a year Yes Onboarding? What onboarding?    No  Never   Start a free trial;Ask developers I know/work with  Amused  Stack Overflow (public Q&A for anyone who codes);Stack Exchange (public Q&A for a variety of topics)    Meditate;Visit Stack Overflow;Do other work and come back later MacOS   "Just me - I am a freelancer, sole proprietor, etc."    NA  Google Cloud Platform   NA  Straight / Heterosexual Yes "No, not at all"    Less than once per month or monthly A few times per month or weekly Easy    Appropriate in length   No  NA  NA  Flask   A lot less welcome now than last year   5   8   3
54  I am a developer by profession  No  44  7   Yearly  160000  160000  United States   United States dollar    USD NA  NA  "Developer, full-stack" "Bachelor’s degree (B.A., B.S., B.Eng., etc.)"  Employed full-time  "White or of European descent;Indigenous (such as Native American, Pacific Islander, or Indigenous Australian)" Man Flex time or a flexible schedule;Remote work options;Opportunities for professional development Very satisfied  I am not interested in new job opportunities    C#;HTML/CSS;JavaScript  C#;HTML/CSS;JavaScript  NA  NA  Github;Gitlab   "Github;Gitlab;Microsoft Teams;Google Suite (Docs, Meet, etc)"  No  Neutral Very important  Better compensation;Trouble with my direct manager;Trouble with leadership at my company;Better work/life balance;Wanting to work with new technologies;Growth or leadership opportunities  Publicly available financial information (e.g. Crunchbase);Personal network - friends or family;Directly asking current or past employees at the company    Once every few years    Not sure    No  No  Sometimes: 1-2 days per month but less than weekly  NA  Indifferent Stack Overflow (public Q&A for anyone who codes);Stack Exchange (public Q&A for a variety of topics)    Visit Stack Overflow;Go for a walk or other physical activity   Windows "10,000 or more employees"  NA  NA  I have little or no influence   NA  No  "No, not really"    NA  Daily or almost daily   Neither easy nor difficult  Appropriate in length   No  "Computer science, computer engineering, or software engineering"   NA  jQuery  Somewhat more welcome now than last year    40  38  23
56  I am a developer by profession  Yes 27  21  NA  NA  NA  United States   United States dollar    USD Elasticsearch   DynamoDB;MySQL;Redis    "Developer, full-stack" "Bachelor’s degree (B.A., B.S., B.Eng., etc.)"  Employed full-time  White or of European descent    Woman   Diversity of the company or organization;Specific department or team I’d be working on;Office environment or company culture    Very satisfied  I am not interested in new job opportunities    Python;TypeScript   HTML/CSS;JavaScript;PHP;Python;SQL;TypeScript   Unity 3D;Unreal Engine  NA  Gitlab;Slack;Stack Overflow for Teams   Confluence;Jira;Github;Gitlab;Slack Yes Neutral Somewhat important  Trouble with my direct manager;Trouble with leadership at my company    "Company reviews from third party sites (e.g. Glassdoor, Blind);Read other media like news articles, founder profiles, etc. about the company"  Once a year Not sure    No  No  Never   NA  Indifferent Stack Overflow (public Q&A for anyone who codes);Stack Exchange (public Q&A for a variety of topics)    Play games;Call a coworker or friend;Visit Stack Overflow;Go for a walk or other physical activity;Do other work and come back later    MacOS   500 to 999 employees    Docker;Kubernetes;Linux Docker;Linux    I have little or no influence   Straight / Heterosexual Yes "Yes, definitely"   Daily or almost daily   Multiple times per day  Easy    Appropriate in length   No  "A natural science (such as biology, chemistry, physics, etc.)" Django  Symfony Just as welcome now as I felt last year 40  6   4
57  I am a developer by profession  No  44  12  Monthly 135000  1620000 United States   United States dollar    USD SQLite  SQLite  "Database administrator;Designer;Developer, back-end;Developer, desktop or enterprise applications;Developer, front-end;Developer, full-stack;Product manager"  "Master’s degree (M.A., M.S., M.Eng., MBA, etc.)"   Employed full-time  White or of European descent    Man Industry that I’d be working in;Specific department or team I’d be working on;Office environment or company culture Very satisfied  "I’m not actively looking, but I am open to new opportunities"  C#  C#;VBA  .NET;.NET Core  .NET    "Github;Trello;Google Suite (Docs, Meet, etc)"  "Github;Trello;Google Suite (Docs, Meet, etc)"  No  Somewhat important  Fairly important    Just because;Curious about other opportunities  NA  Once a decade   Yes Onboarding? What onboarding?    Yes Rarely: 1-2 days per year or less   Start a free trial;Visit developer communities like Stack Overflow;Read ratings or reviews on third party sites like G2Crowd    Amused  Stack Overflow (public Q&A for anyone who codes);Stack Exchange (public Q&A for a variety of topics)    Visit Stack Overflow;Go for a walk or other physical activity;Watch help / tutorial videos;Do other work and come back later;Visit another developer community (please name):   Windows "10,000 or more employees"  Android;Arduino;Windows Windows I have some influence   Straight / Heterosexual Yes "Yes, definitely"   Daily or almost daily   Multiple times per day  Easy    Appropriate in length   No  "Computer science, computer engineering, or software engineering"   NA  NA  Just as welcome now as I felt last year 43  33  23


and this is a snippet of my code (Note that person[3] is the age field I am trying to sum up):

   private int calculateAverage() {
        try {
            BufferedReader reader = new BufferedReader(new FileReader("survey_results_public_subset.tsv"));

            String line ;
            String splitBy = "t";

            while ((line = reader.readLine()) != null) {

                String[] person = line.split(splitBy);

                if (person[3].equals("NA") || person[3].contains(".") || !person[5].equals("Yearly") || person[22].equals("NA")) {
                    reader.readLine();
                } else {

                    int age = Integer.parseInt(person[3]);

                    System.out.println(age);

                }

            }


        } catch (IOException e) {
        }
        return 0;
    }

Also, is there a better way to filter my if statement conditions more efficiently?

2

Answers


  1. Here is refactored version using Stream API:

        private static int calculateAverage() throws IOException {
                int ageColumn = 3;
                return Files.readAllLines(Paths.get("survey_results_public_subset.tsv")).stream()
                        .map(line -> line.split(" "))
                        .skip(1) // header line
                        .filter(columns -> !columns[ageColumn].equals("NA")
                                && !columns[ageColumn].contains(".")
                                && !columns[5].equals("Yearly")
                                && !columns[22].equals("NA"))
                        .mapToInt(columns -> {
                            try {
                                return Integer.parseInt(columns[ageColumn]);
                            } catch (NumberFormatException e) {
                                return 0;
                            }
                        })
                        .sum();
        }
    

    Make sure that your .tsv file has t symbol as a delimiter.

    Login or Signup to reply.
  2. Here is another round about way to accomplish this task (read the comments in code):

     public static int calculateAverageAge(String tsvFilePath) {
        int validAgeCounter = 0;
        int ageSum = 0;
        // 'Try With Resources' used here so to auto-close BufferedReader.
        try (BufferedReader reader = new BufferedReader(new FileReader(tsvFilePath))) {
            String line ;
            String splitRegEx = "t";   // Split file data line based on a single tab delimiter.
            
            while ((line = reader.readLine()) != null) {
                String[] person = line.split(splitRegEx);
                if (person[3].matches("\d+") || person[5].equals("Yearly") || !person[22].equals("NA")) {
                    int age = Integer.parseInt(person[3]);  // Convert string age to Integer (int).
                    // Is the age within a reasonable age range?
                    // (set the range to what you want)
                    if (age > 5 && age < 120) {
                        // Yes ... It is! 
                        // Age is valid (meets the various criteria) 
                        // so increment the Valid Age Counter  
                        validAgeCounter++;  
                        ageSum += age;  // Maintain a running total of Ages
                    }
                } 
            }
        }
        catch (FileNotFoundException ex) {
            System.err.println(ex);
        }
        catch (IOException ex) {
            System.err.println(ex);
        }
        
        int average = ageSum / validAgeCounter;  // Get Average - 'Total Valid Ages' divided by 'Number Of Valid Ages'
        return average;     // Return the calculated Average Age
    }
    

    Note that the String#matches() method can eliminate a lot of specific if statement conditions. When the "\d+" Regular Expression (RegEx) is used as an argument for the matches() method, it will return boolean true if the string it is used against contains nothing but integer digits and boolean false if not.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search