Link to home
Start Free TrialLog in
Avatar of geeta_m9
geeta_m9

asked on

How do I get all the error messages to appear when doing validation in the constructor?

I am not getting all the error messages to appear when doing validation within the constructor. I am not sure what I am omitting. I am using IntelliJ with JDK 11.0.8

ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of geeta_m9
geeta_m9

ASKER

This is my citydata java class

public class CityData
{
    private long id = 0;
    private String city = "";
    private String latitude = "";
    private String longitude = "";
    private String country = "";

    // constructors
    public CityData(String csvData, String separator) throws Exception
    {
        String[] fields = csvData.split("\t");

        if (fields.length < 5)
        {
            throw new Exception(String.format("Invalid number of fields found: expected %d, found %d", 5, fields.length));
        }

        if (fields.length > 5)
        {
            throw new Exception(String.format("Invalid number of fields found: expected %d, found %d", 5, fields.length));
        }

        //this.id = Long.parseLong(fields[0]);
        //this.city = fields[1];
        //this.latitude = fields[2];
        //this.longitude = fields[3];
       // this.country = fields[4];

        this.setId(fields[0]);
        this.setCity(fields[1]);
        this.setCountry(fields[3]);
        this.setLatitude(fields[2]);
        this.setLongitude(fields[4]);
    }

    // accessors and mutators aka getters and setters

    public String getCity()
    {
        return this.city;
    }

    public long getId()
    {
        return id;
    }

    public void setId(String idStr)
    {
        // if idStr == "abc"
        // if idStr == "123"
        this.id = Long.parseLong(idStr);
    }

    public void setId(long id)
    {
        this.id = id;
    }

    public String getLatitude(String latitude)
    {
        return latitude;
    }

    public void setLatitude(String latitude) throws Exception
    {
        // Check to see if the latitude value is within the correct range, i.e, between -90 and +90
        if (Double.parseDouble(latitude) < -90 || Double.parseDouble(latitude) > 90)
        {
            throw new Exception(String.format("Latitude value is not within the correct range"));
        }
        this.latitude = latitude;
    }

    public String getLongitude()
    {
        return longitude;
    }

    public void setLongitude(String longitude) throws Exception
    {
        // Check to see if the longitude value is within the correct range, i.e., between -180 and +180
        if  (Double.parseDouble(longitude) < -180 || Double.parseDouble(longitude) > 180)
        {
            throw new Exception(String.format("Longitude value is not within the correct range"));
        }
        this.longitude = longitude;
    }

    public String getCountry()
    {
        return country;
    }

    public void setCountry(String country) throws Exception
    {   char c1;
        char c2;

         if (country.isBlank())
         {
            throw new Exception(String.format("Country code is blank"));
         }
        else
        {   // Check to see if the country code field is of length 2
            if (country.length() !=2)
            {
                throw new Exception("Country code is not of length 2");
            }
            //Check to see if the country code is alphabetic
            else
            {
                c1 = country.charAt(0);
                c2 = country.charAt(1);
                if (!(Character.isAlphabetic(c1))  || !(Character.isAlphabetic(c2)))
                {
                    throw new Exception(String.format("Country code is not a two-letter alphabetic code"));
                }
            }
        }
        this.country = country;
    }

    public void setCity(String city) throws Exception
    {
        if (city.isBlank())
        {
           throw new Exception(String.format("City name is blank"));
        }
        this.city = city;
    }

}

Open in new window

This is my Main. java class


import java.io.File;
import java.io.FileNotFoundException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.TreeMap;

import static java.lang.System.*;

public class Main {

    public static void main(String[] args)
    {
        Scanner kbd = new Scanner(in);
        out.print("Enter file name: ");
        String fileName = kbd.nextLine();
        File fIn = new File(fileName);
        Scanner fileScanner = null;

        try
        {
            fileScanner = new Scanner(fIn);
        }
        catch (FileNotFoundException e)
        {
            err.println("Could not find that file!");
            exit(1);
        }

        String line = "";

        ArrayList<CityData> cityList = new ArrayList<>();

        ArrayList<String> errors = new ArrayList<>();

        HashMap<String, Integer> cityMap = new HashMap<>();

        int lineCount = 0;
        while (fileScanner.hasNextLine())
        {
            line = fileScanner.nextLine().trim();

            lineCount += 1;

            if (line.length() == 0 || line.startsWith("#"))
            {
                continue;
            }

            CityData cd = null;
            try
            {
                cd = new CityData(line, "\t");
            }
            catch (NumberFormatException e)
            {
//              System.out.println("Could not convert field to Long");
                errors.add(String.format("Could not convert field to long at line %d", lineCount));
                continue;
            }
            catch (Exception e)
            {
//              System.out.println(e.getMessage());
                errors.add(String.format("%s at line %d", e.getMessage(), lineCount));

                continue;
            }

            cityList.add(cd);

            int count = 0;
            if (cityMap.containsKey(cd.getCountry()))
            {
                // extract the value (count) for this country, it's an int
                // increment the count
                // put the new count back in the structure
                count = cityMap.get(cd.getCountry());
                count += 1;
                cityMap.put(cd.getCountry(), count);
            }
            else
            {
                cityMap.put(cd.getCountry(), 1);
            }

//            System.out.println(cd.getCity());
        }

//        for (String country : cityMap.keySet())
//        {
//            System.out.println(String.format("In %s, there are %d cities!", country, cityMap.get(country)));
//        }

        TreeMap<String, Integer> cityTree = new TreeMap<>(cityMap);

        for (String country : cityTree.keySet())
        {
            System.out.println(String.format("In %s, there are %d cities!", country, cityTree.get(country)));
        }

        out.println(String.format("There are %d Cities/Countries in the dataset", cityList.size()));

        // Prompt the user if they want to see the list of errors encountered
        Scanner scan = new Scanner(System.in);

        System.out.print("Enter 'Y' if you would like to see the list of errors: ");
        String sc = scan.nextLine();

        System.out.print(sc);

        if (sc.equals("Y"))
       {
            if (errors.size() > 0)
            {
                for (String s : errors)
                {
                    err.println(s);
                }
            }
        }
    }
}

Open in new window





I am not sure how to call the constructors, e.g., setID, setCity for each of the components within the class CityData.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
:)
Also, prefer subclasses of RuntimeException as unchecked exceptions are easier to handle. Prefer also existing classes, e.g. IllegalArgumentException etc.
Your csv field length check only needs to happen once, based on equality