1  import java.io.File;
  2  import java.io.FileNotFoundException;
  3  import java.io.PrintWriter;
  4  import java.util.Scanner;
  5  
  6  /**
  7     This program reads data files of country populations and areas and prints the
  8     population density for each country.
  9  */
 10  public class PopulationDensity
 11  {
 12     public static void main(String[] args) throws FileNotFoundException
 13     {
 14        // Construct Scanner objects for input files
 15  
 16        Scanner in1 = new Scanner(new File("worldpop.txt")); 
 17        Scanner in2 = new Scanner(new File("worldarea.txt"));
 18  
 19        // Construct PrintWriter for the output file
 20  
 21        PrintWriter out = new PrintWriter("world_pop_density.txt"); 
 22  
 23        // Read lines from each file
 24  
 25        while (in1.hasNextLine() && in2.hasNextLine())
 26        {
 27           String line1 = in1.nextLine();
 28           String line2 = in2.nextLine();
 29  
 30           // Extract country and associated value
 31           String country = extractCountry(line1);         
 32           double population = extractValue(line1);
 33           double area = extractValue(line2);
 34  
 35           // Compute and print the population density
 36           double density = 0;
 37           if (area != 0) // Protect against division by zero
 38           {
 39              density = population / area;
 40           }
 41           out.printf("%-40s%15.2f\n", country, density);
 42        }
 43        
 44        in1.close();
 45        in2.close();
 46        out.close();
 47     }
 48  
 49     /**
 50        Extracts the country from an input line.
 51        @param line a line containing a country name, followed by a number
 52        @return the country name
 53     */
 54     public static String extractCountry(String line)
 55     {   
 56        int i = 0; // Locate the start of the first digit
 57        while (!Character.isDigit(line.charAt(i))) { i++; }
 58        return line.substring(0, i).trim(); // Extract the country name
 59     }
 60  
 61     /**
 62        Extracts the value from an input line.
 63        @param line a line containing a country name, followed by a value
 64        @return the value associated with the country
 65     */
 66     public static double extractValue(String line)
 67     {   
 68        int i = 0; // Locate the start of the first digit
 69        while (!Character.isDigit(line.charAt(i))) { i++; }
 70        // Extract and convert the value
 71        return Double.parseDouble(line.substring(i).trim()); 
 72     }
 73  }