rwd
rwd

Reputation: 149

Null return, getting specific data from csv file

I'm trying to get a specific data from the csv file. In this case im using the ID, which is the first String in the file.

animalDetails.txt

0,2,AmercianShorthair,100,AmercianShorthair,AmercianShorthair,y,y,900.0,Ann,
3,4,GermanShepherd,100,GermanShepherd,GermanShepherd,no,yes,600.0,Dave,
6,3,Poodle,100,Poodle,Poodle,yes,no,300.0,Dianna,
456,4,Azawakh,50,Unknown,Azawakh,no,no,300.0,April,
25041019042018,1,Vizsla,50,Vizsla,TreeingTennesseeBrindle,no,yes,500.0,Lex,
3271,1,Beagle,50,Beagle,Unknown,no,no,200.0,Blanton,
48331827032019,33,sheperd,50,50,50,no,yes,300.0,Mike,

MainApp

public class AppTest {

    public static void main(String[] ages) {

        //Load file 
        AnimalManager aMgr = new AnimalManager();
        aMgr.loadFromFile("AnimalDetails.txt");     

        //Test DELETE By Animal ID
        try {
        Animals anim = aMgr.getAnimalById("0");//Insert animal ID here
        aMgr.deleteAnimal(anim);
        } catch (IllegalArgumentException exc) {
          System.out.println(exc);
        }
    }
}

Manager

//Delete animal
public void deleteAnimal (Animals a) {
    if (a == null)
        throw new IllegalArgumentException("Animal argument is null");

    animalList.remove(a);
}

//Get animal by ID
public Animals getAnimalById(String ID) {
    for (Animals a : this.animalList) {
        if (a.getID().equals(ID))
            return null;     
    }
    return null;
}

When I insert animal ID in the main app, it returns me back null instead of the successful deletion message. What could be the issue here?

output: java.lang.IllegalArgumentException: Animal argument is null

Upvotes: 1

Views: 82

Answers (2)

mvmn
mvmn

Reputation: 4057

First, you always return null from getAnimalById. You should change it to be this:

public Animals getAnimalById(String ID) {
    for (Animals a : this.animalList) {
        if (a.getID().equals(ID))
            return a;     
    }
    return null;
}

Second, it wouldn't harm to have a null-check in a code like this:

Animals anim = aMgr.getAnimalById("0");//Insert animal ID here
if(anim!=null) aMgr.deleteAnimal(anim);

Although I suppose this particular code is there just as an example. But still - there is a possibility that animal with given ID is not in the list, so in general a null-check should be placed in such kind of code, because I suppose you don't specifically want your program to fail with exception in such case.

Upvotes: 1

David Silveiro
David Silveiro

Reputation: 1602

Looks like the conditional statement should return the ID instead of null for getanimalbyID :)

Upvotes: 2

Related Questions