简体   繁体   中英

Adding lines of varying length to a 2d arraylist

I am looking to open a text file which is formatted as follows and to put it into an 2d arraylist where each object (and not each line) has its own index.

5
1 a w e r s 5 2 d 6
f s d e a 3 6 7 1 32
2 f s 6 d
4 s h y 99 3 s d
7 s x d q s 

I have tried many solutions, most of those involving a while(scanner.hasNext()) or while(scanner.hasNextLine()) loops, assigning all the objects in a row to their own indice in a 1d arraylist, and then adding that arraylist to a 2d arraylist. But no matter what I do I do not get the result I want.

What I am in essence trying to do is something such as the scanner .hasNext() method which only grabs the next object within a line, and will not jump to the next line. An example of one of my tries is as follows:

while (scanner.hasNextLine()) {
   ArrayList<Object> array = new ArrayList<Object>();
     while(scanner.hasNext()0 {    

         String line = scanner.next();
         array.add(line);
        }

        System.out.println(array);
        2dArray.add(array);
    }

    scanner.nextLine();
}

You need to allocate a new array each time through the outer loop, rather than clearing the existing array. Also, it might be easiest to set up a new Scanner for each line:

while (scanner.hasNextLine()) {
    String line = scanner.nextLine();
    Scanner lineScanner = new Scanner(line);
    ArrayList<String> array = new ArrayList<String>();
    while (lineScanner.hasNext()) {
        array.add(lineScanner.next());
    }
    my2Darray.add(array);
}

Use a BufferedReader to read the file one line at atime.

BufferedReader br = new BufferedReader(...);
while ((strLine = br.readLine()) != null) {
   String[] strArray = strLine.split("\\s");
   // do stuff with array
}

Then split the String on spaces, which gives you a String[], and is easily converted into a List. Something like this: How do I split a string with any whitespace chars as delimiters?

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