I am looking for a way to read a tab delimited file of baseball stats into a two dimensional arraylist. I'm using a scanner to read the file, but I can't think of how to read just one line into an array list, stopping at the line break, then read the next line into the next arraylist.
This is my first time trying to create a multidimensional arraylist, and I thought it would be much the same as reading multidimensional arrays. I was clearly mistaken.
public static ArrayList dataRead(String fileloc) throws FileNotFoundException {
ArrayList array = new ArrayList<ArrayList>();
Scanner s = new Scanner(new File(fileloc)).useDelimiter("\t");
ArrayList<String> rows = new ArrayList<String>();
ArrayList cols = new ArrayList();
while(s.nextLine() != null) {
cols.add(s.next());
}
return array;
}
This is my code as of now. Would it be a better choice to read each line into a string, delimited by returns, then read each string into an appropriate arraylist?
You could use opencsv and set the delimeter to tab. Check out the examples on the link I provided.
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), '\t');
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
// nextLine[] is an array of values from the line
System.out.println(nextLine[0] + nextLine[1] + "etc...");
}
Although it's not clear from your question what your actual issue is when trying to 'roll your own'
I'm not sure what the stats look like, but it might be better to use a HashMap which has Key/value pairs instead, but I could be wrong. I don't know what your dataset looks like.
For a start, you can delimit the lines by using the "\t" escape character. For Example:
Scanner s = new Scanner(input).useDelimiter("\t");
Then you can loop through the results and for every pair add it to the map.
The useDelimiter was a big part of what I was forgetting, thanks for bringing it up - gelliott181 2012-04-04 18:35
I think you need to rethink your data structure to something more conducive to what you are trying to store. I would recommend that you create a player object and store that into an arraylist.
public class Player{
double battavg;
String name;
//add more values like rbi, etc.
public Player(name,battavg){
this.name=name;
this.battavg=battavg;
}
public String getName(){
return name;
}
public String getBattAvg(){
return battavg;
}
public setBattAvg(double battavg){
this.battavg=battavg;
}
public setName(String name){
this.name=name;
}
}
public class baseball{
public static void main(String[] args){
ArrayList<Player> list = new ArrayList<Player>();
//read in values from csv
list.add(new Player(name,battavg));
}
}