List of List in for loops Java -
i have problem. try develop program ask me numbers few times. give list of numbers. try save them in list>. numbers can split space. have code :
import java.util.arraylist; import java.util.list; import java.util.scanner; public class timeseries { public static void main(string[] args) { // todo auto-generated method stub system.out.println("numbers of rows:"); scanner in = new scanner(system.in); int numberlines = in.nextint(); in.nextline(); string ciag; list<list<integer>> ll = new arraylist<list<integer>>(); list<integer> list = new arraylist<integer>(); (int = 0; < numberlines; i++) { list.clear(); system.out.println("add row " +(i+1)); ciag = in.nextline(); (int t=0; t<ciag.length(); t++) { if(character.iswhitespace(ciag.charat(t))) { } else {list.add(character.getnumericvalue(ciag.charat(t))); } } system.out.println(list); ll.add(list); } system.out.println(ll); } }
but output (example) :
numbers of rows: 3 add row 1 0 0 0 [0, 0, 0] add row 2 1 2 3 [1, 2, 3] add row 3 54 6 8 [5, 4, 6, 8] [[5, 4, 6, 8], [5, 4, 6, 8], [5, 4, 6, 8]]
but need have [[0,0, 0], [1, 2, 3], [5, 4, 6, 8]]
the problem add the same list
ll
multiple times. need add different lists behavior want. that, need create fresh new list in each iteration of for
loop, instead of clearing , reusing existing list
.
change these lines:
list<list<integer>> ll = new arraylist<list<integer>>(); list<integer> list = new arraylist<integer>(); (int = 0; < numberlines; i++) { list.clear();
to this:
list<list<integer>> ll = new arraylist<>(); (int = 0; < numberlines; i++) { list<integer> list = new arraylist<>();
Comments
Post a Comment