简体   繁体   中英

Outputting contents of a 2d arrayList

Im strugging to get this code to work. What is supposed to happen is it creates an 2d arraylist, then adds some arraylist to that 2darraylist. Then taking user input and adding it to 2d array and tokenise it. Then output those tokenised inputs. The output should be so the first line will show the first arrayList then the second line will show the contents of the second arraylist and so on. Im getting the error message outofbound, size 5 size 5.

    String transState;
    trans = new ArrayList<List<String>>(5);
    ArrayList<String> t = new ArrayList<String>(5);
    for (i = 1; i < 5; i++) {
    trans.add(t);
    }
    for (i = 1; i < 5; i++) {

        for (j = 0; j < 5; j++){
            transState = s.nextLine();
            trans.get(i).get(j).add(transState);
            trans.get(i).get(j).split(transState);
        }
    }
    for (i = 0; i < 5; i++) {
        for (j = 0; j < 5; j++) {  
            System.out.println( trans.get(i).get(j) );
        }
    }

Seems like the problem is here:

ArrayList<String> t = new ArrayList<String>(5);
for (j = 0; j < 5; j++)
    trans.add(t);

You're adding the same ArrayList several times when you should add different ArrayList s into the principal ArrayList , like this:

for (j = 0; j < 5; j++) {
    ArrayList<String> t = new ArrayList<String>(5);
    trans.add(t);
}

Apart of this, you will have a problem here:

trans.get(i).get(j).add(transState);

It should be

trans.get(i).add(transState);
//trans.get(i) returns List<String>

Also, this line makes no sense as is:

trans.get(i).get(j).split(transState);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM