How to read in a file of numbers into an array list in Java -
i want able read in map file looks like:
0, 0, 0, 0, 0
0, 0, 1, 0, 0
0, 1, 1, 1, 1
0, 1, 1, 1, 0
0, 0, 1, 1, 0
and create array list looks like:
{[0, 0, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 1, 1, 1, 1],
[0, 1, 1, 1, 0],
[0, 0, 1, 1, 0]}
i have tried using br.readline() appears getting stuck not throwing error in middle.
public static int[][] loadfile() throws ioexception{
filereader in = new filereader(main.currentfilepath + main.currentfile); bufferedreader br = new bufferedreader(in); string line; int [] intarray = {}; int [][] filearray = {}; int j = 0; while ((line = br.readline()) != null) { list<string> stringlist = new arraylist<string>(arrays.aslist(line.split(","))); string[] stringarray = stringlist.toarray(new string[0]); list<integer> intlist = new arraylist<integer>(); system.out.println("rrrrr"); for(int = 0; < stringlist.size(); i++) { scanner scanner = new scanner(stringarray[i]); system.out.println("ggggg"); while (scanner.hasnextint()) { intlist.add(scanner.nextint()); intarray = intlist.parallelstream().maptoint(integer::intvalue).toarray(); system.out.println("ffff"); } system.out.println(filearray[j][i]); filearray[j][i] = intarray[i]; } j++; } return filearray; }
the basic problem is, you're declaring array of 0
length (no elements), makes impossible add elements it.
int [][] filearray = {};
unless know in advance number of rows/columns need, arrays not helpful, instead, make use of list
of kind, example...
list<int[]> rows = new arraylist<>(5); int maxcols = 0; try (bufferedreader br = new bufferedreader(new filereader(new file("test.txt")))) { string text = null; while ((text = br.readline()) != null) { system.out.println(text); string[] parts = text.split(","); int[] row = new int[parts.length]; maxcols = math.max(maxcols, row.length); (int col = 0; col < parts.length; col++) { row[col] = integer.parseint(parts[col].trim()); } rows.add(row); } } catch (ioexception ex) { ex.printstacktrace(); } int[][] map = new int[rows.size()][maxcols]; (int row = 0; row < rows.size(); row++) { map[row] = rows.get(row); }
my "personal" gut feeling not bother arrays @ , make use of compound list
s...
list<list<integer>> rows = new arraylist<>(5); try (bufferedreader br = new bufferedreader(new filereader(new file("test.txt")))) { string text = null; while ((text = br.readline()) != null) { system.out.println(text); string[] parts = text.split(","); list<integer> row = new arraylist<>(parts.length); (string value : parts) { row.add(integer.parseint(value.trim())); } rows.add(row); } } catch (ioexception ex) { ex.printstacktrace(); }
Comments
Post a Comment