How can I get my if statement to work properly when a csv value does not exist?

The issue I am currently having is that my IF statement for my CVSParser is not working. The countryname “Germany” doesn’t exist which is ok but the string notf is not returning when this error occurs instead I get:

“java.lang.IllegalArgumentException: Mapping for Germany not found, expected one of [Country, Exports, Value (dollars)]”.

I assumed the value that was being returned was a null value because CVSParser returns a String, however, assigning a null value to countryName is not getting my code to work.

The issue came up when I was using tester.

What steps do I need to take to fix? Also in general how I do figure out the value a method is returning when what it’s looking for doesn’t exist? (Specifically when it’s not in the documentation.)

public String countryInfo (CSVParser parser,String country){
    FileResource fr = new FileResource();
    String exports= "";
    String countryName= "";
    String value= "";
    for (CSVRecord record : parser){
        exports=record.get("Exports");
        countryName=record.get(country);
        value= record.get("Value");
        if (exports== null ||countryName!= country){
            String notf= "info has not been found";
            return notf;
        }
    }
    String info= countryName +":"+ exports;
    return info;
}

public void tester (){
    FileResource fr = new FileResource();
    CSVParser parser = fr.getCSVParser();
    countryInfo(parser,"Germany");
}

Answer

@HovercraftFullOfEels remarks about string comparison are right.

But the exception says

“java.lang.IllegalArgumentException: Mapping for Germany not found, expected one of [Country, Exports, Value (dollars)]”

and the test code results in a call

countryName=record.get("Germany");

where the exception suggests it should have been

countryName=record.get("Country");

So if you want information about Germany’s exports, the code should be

public String countryInfo (CSVParser parser,String desiredCountry){
     FileResource fr = new FileResource();
     String exports= "";
    String countryName= "";
     String value= "";
    for (CSVRecord record : parser){
      exports=record.get("Exports");
      countryName=record.get("Country");
      value= record.get("Value");
      if (exports== null || !countryName.equals(desiredCountry)){
        String notf= "info has not been found";
        return notf;
      }
    }
    String info= countryName +":"+ exports;
    return info;
       }
public void tester (){
        FileResource fr = new FileResource();
        CSVParser parser = fr.getCSVParser();
        countryInfo(parser,"Germany");
       }

Leave a Reply

Your email address will not be published. Required fields are marked *