d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Csv Into Arraylist Java > Wat Do
Add Reply New Topic New Poll
Member
Posts: 5,167
Joined: Nov 23 2006
Gold: 11.01
Oct 3 2014 02:15pm
I'm not sure how to read from a CSV into an arraylist in java.

I have an arraylist of items and in my method I have instantiated ArrayList<Item> itemz = new ArrayList<Item>();

I have to fill itemz with items from the CSV which have String, Int, Int values in them. Then return itemz;

Is this correct? I believe all the logic is correct but I can't compile/test it due to not even being near done with the other classes in the assignment.


Code
public ArrayList<Item> getGameItems(String filePath)
{
ArrayList<Item> itemz = new ArrayList<Item>();
try{
Scanner data = new Scanner(new File(filePath));
while(data.hasNextLine())
{
String next = data.nextLine();
if(!next.trim().isEmpty())
{
String[] dataz = next.split(",");
String name = dataz[0];
int value = Integer.parseInt(dataz[1]);
int weight = Integer.parseInt(dataz[2]);
itemz.add(new Item(name,value,weight));

}
}
data.close();
}catch (FileNotFoundException e){
e.printStackTrace();
}
return itemz;
}
Member
Posts: 2,757
Joined: Nov 26 2007
Gold: 1,214.81
Oct 3 2014 02:35pm
Looks fine to me. Why can't you test it?

Just make an Item class
Item.java
Code
public class Item{
String name;
int value;
int weight;
public Item(String name, int value, int weight){
this.name=name;
this.value=value;
this.weight=weight;
}

@Override
public String toString(){
return name + " " + value + " " + weight;
}
}


Main.java
Code
public static void main(String[] args){
List<Item> items = getGameItems("filename.csv");
for(Item item : items){
System.out.println(item);
}
}


Member
Posts: 5,167
Joined: Nov 23 2006
Gold: 11.01
Oct 3 2014 02:43pm
Quote (labatymo @ Oct 3 2014 03:35pm)
Looks fine to me. Why can't you test it?

Just make an Item class
Item.java
Code
public class Item{
String name;
int value;
int weight;
public Item(String name, int value, int weight){
this.name=name;
this.value=value;
this.weight=weight;
}

@Override
public String toString(){
return name + " " + value + " " + weight;
}
}


Main.java
Code
public static void main(String[] args){
List<Item> items = getGameItems("filename.csv");
for(Item item : items){
System.out.println(item);
}
}


Sorry... I guess I meant I'm too lazy to test it right meow xD

Programming on a laptop with only touchpad sucks -.-
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Oct 3 2014 05:16pm
Quote (HoneyBadger @ Oct 3 2014 04:43pm)
Sorry... I guess I meant I'm too lazy to test it right meow xD

Programming on a laptop with only touchpad sucks -.-


i use just the touchpad all day at work.
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll