Suppose you are given a large file with all of the ages (in years) of a large number of people. The minimum age is 1 year and the maximum is 200 years of age. Each line of the file has the form name:age where name is a string (that may have spaces) and age is a positive integer representing a person's age.

For example,
Bob Smith:45
Lester Tester:39

would be valid lines of the file. You may assume that the file is well formed and does not need to be validated. However as the file could be very large, you can not hold it all in memory.

Give a program that efficiently writes how many people there are of each age in the file whose name is given as a command line argument. That is for each age that exists in the file, print a line of the form "There were x people of age y." Note no names are to be listed.

While you may assume the file is valid, you must still handle any IO related exceptions correctly.

Solution PreviewSolution Preview

These solutions may offer step-by-step problem-solving explanations or good writing examples that include modern styles of formatting and construction of bibliographies out of text citations and references. Students may use these solutions for personal skill-building and practice. Unethical use is strictly forbidden.

public class Age {

public static void main(String[] arg) throws IOException {
// Checking if there is more than one line argument and printing the appropriate message
if (arg.length != 1) {
    System.err.println("Please provide only one command line argument, for the file that has to be read");

// Reading the file and initializing the buffers
// Throwing an exception if there is a problem with opening the file
// That checking is done in the separate method br (listed below)
File file = new File(arg[0]);   
FileReader fr = new FileReader(file);   
BufferedReader b = br(arg[0]);

StringBuffer sb = new StringBuffer();   
String line;

// Storing the content of the file in String buffer

By purchasing this solution you'll be able to access the following files:

for this solution

or FREE if you
register a new account!

PayPal, G Pay, ApplePay, Amazon Pay, and all major credit cards accepted.

Find A Tutor

View available Java Programming Tutors

Get College Homework Help.

Are you sure you don't want to upload any files?

Fast tutor response requires as much info as possible.

Upload a file
Continue without uploading

We couldn't find that subject.
Please select the best match from the list below.

We'll send you an email right away. If it's not in your inbox, check your spam folder.

  • 1
  • 2
  • 3
Live Chats