I’d like to create a dynamic Multidimensional ArrayList that reads from a text file with integers separated by spaces, and by lines looking something like this:
0 -5 5 0 -3 0 5
3 1 0 0 0 0 5
5 -5 0 5 5 1 1
(Just a tiny fraction of actual data, and rows and columns are subject to change, hence the need for a dynamic 2D ArrayList.)
So far this is what I have in code:
ArrayList<ArrayList<Integer>> ratings2DArray = new ArrayList<ArrayList<Integer>>();
try {
in = new BufferedReader(new FileReader("PureRatings.txt"));
int counter = 0;
while (in.readLine() != null) {
ratings2DArray.add(new ArrayList<Integer>()); //Adds 2nd dimension.
^ Pretty much saying that for each line in the text file, add a row to the 2D ArrayList.
Down here I need to declare a string (or char?) variable called rating that takes the input from the text file.
And have it be delimited by spaces (sorry if I am not using the terminology correctly) so that each character “-5″,”-3″,”0″,”3″,”5″ is put inside the ArrayList individually.
ratings2DArray.get(counter).add(Integer.parseInt(rating));
counter ++;
}
in.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
This is barely my second semester with any exposure to programming, so any answers/ advice on whether or not this is feasible, efficient, inefficient, if I should be using different data structures, et cetera, would be greatly appreciated.
You’re headed in the right direction. Remember to always organize your code into logical units, it helps with the conceptualization process, and the maintenance of your program down the line.
You should handle NumberFormatExceptions that can arise while you are parsing individual integers. You will notice I dropped the
countervariable, it makes your program more complicated and could be the source of bugs. Good luck with the rest of the homework.