Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function called readCountries that reads a file and returns a list of co

ID: 3762789 • Letter: W

Question

Write a function called readCountries that reads a file and returns a list of countries. The countries should be read from a file (countries.txt), which contains an incomplete list of countries with their area and population. Each line in this file represents one country in the following format:

name, area(in km2), population

When opening the file your function should handle any exceptions that may occur. Your function should completely read in the file, and separate the data into a 2-dimensional list. You may need to split and strip the data as appropriate. Numbers should be converted to their correct types

Explanation / Answer


import java.io.File;
import java.util.Scanner;

public class ReadCountries {

   /**
   * @param args
   */
   public static void main(String[] args) {
       // TODO Auto-generated method stub
       try {
           File countries= new File("countries.txt");
           Scanner input = new Scanner(countries);
           readCountries(input);
       } catch (Exception e) {
           // TODO: handle exception
       }

   }

   public static void readCountries(Scanner input) {
       try {
           while (input.hasNextLine()) {
               String line = input.nextLine();
               String lineArray[] = line.split(" ");
               String countryName = lineArray[0];
               double area = Double.parseDouble(lineArray[1]);
               int population = Integer.parseInt(lineArray[2]);
               System.out.println(countryName + " " + area + " " + population);

           }
       } catch (NumberFormatException nfe) {
           nfe.printStackTrace();
           // TODO: handle exception
       }
   }

}

countries.txt

india 100.455 10000
USA 100.98 12000
UK 100.786 5000

OUTPUT :

india 100.455 10000
USA 100.98 12000
UK 100.786 5000

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote