0

SO, here goes my choppy explanation of my choppy title.

I have a csv file, and it contains, at the moment

id,name,hp,atk,def,desc
1,Man,10,5,5,A man
2,Woman,10,5,5,A woman
3,Goblin,15,7,3,A goblin ack!

I am trying to take the information from this csv file, send it to an ArrayList, instantiate the ArrayList using the Constructor I have for NPCs so that later on I can use these NPCs as objects -- if that makes sense.

I think I have like some of this done already, I just don't know how to read integers from the CSV file.

public class NPCLoader {
    
    private static final String dir = "./data/npcs.csv";
    public static ArrayList<NPCHandler> npcs = new ArrayList<NPCHandler>();
    
    public static void main(String args[]) {
        loadNpcs();
    }

    private static void loadNpcs() {
        BufferedReader br = new BufferedReader(new FileReader(new File(dir)));
        String line = null;
        while((line = br.readLine()) != null) {
            String[] n = line.split(",");
            NPCHandler npc = new NPCHandler(n[0], n[1], n[2], n[3], n[4], n[5]);//issue is here, it wants me to change my constructor to String String String String String when it needs to be int String int int int String
            npcs.add(npc);
        }
    }

}

Here is my constructor for the NPCHandler if you need to see it

public class NPCHandler {
    
    private int id;
    private String name;
    private int hp;
    private int atk;
    private int def;
    private String desc;
    
    
    public NPCHandler(int id, String name, int hp, int atk, int def, String desc) {
        this.id = id;
        this.name = name;
        this.hp = hp;
        this.atk = atk;
        this.def = def;
        this.desc = desc;
    }
//Get setters below

1 Answer 1

1

I think that since you're loading a csv file, every variables are considered strings.

The solution could be to parse some of them to Integer, something like that:

NPCHandler npc = new NPCHandler(Integer.parseInt(n[0]), 
                                n[1], 
                                Integer.parseInt(n[2]),
                                Integer.parseInt(n[3]),
                                Integer.parseInt(n[4]),
                                n[5]);

Reference for string conversion

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.