1

So I'm trying to convert a .txt file in the format of

1 2 3 4 
5 6 7 8
9 1 0 1

into a 2D arraylist of strings. This should also be replicable with any other thing such as

EXTENDING RETRACTING RETRACTING EXTENDING
EXTENDING EXTENDING RETRACTING
RETRACTING

Here's my code

public class Test {
    public static ArrayList<ArrayList<String>> readFromFile(String path) throws FileNotFoundException{
        @SuppressWarnings("resource")
        Scanner in = new Scanner(new File(path));
        ArrayList<ArrayList<String>> comments= new ArrayList<ArrayList<String>>();
        ArrayList<String> words = new ArrayList<String>();
        String[] line;
        String str;
        String [] values;
        while(in.hasNextLine()){
            str=in.nextLine();
            line = str.split("\t");
            values = line[2].split(" ");
            for(String word : values){
                words.add(word);
            }
        }
        comments.add(words);
        return comments;
        }

    public static void main(String[] args) throws FileNotFoundException{
         ArrayList<ArrayList<String>> inputs = readFromFile("/Users/Jason/yaw.txt");
        int k = 0;
        for(int i = 0; i < inputs.size(); i++){
            for(int j = 0; j < inputs.get(k).size(); j++){
                System.out.print(inputs.get(i).get(j));
                k++;
            }
            System.out.println();
        }
    }
}

Currently, it returns this error.

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at Test.readFromFile(Test.java:19)
    at Test.main(Test.java:31)

Any help on how to get this working?

Jason Liu
  • 13
  • 4

2 Answers2

0

You read in a line, then split it with "\t", which gives you an array with 1 value (so length = 1).

lines[2] is therefor out of bounds.

If I understood you correct, then you want to do:

line = str.split("\\s"); // line=[1, 2, 3, 4] for the first line you read

split("\\s") splits all space characters (so not only " ")

If this is not the case, then check what str contains.

Not sure why you do this:

values = line[2].split(" ");
Pinkie Swirl
  • 2,375
  • 1
  • 20
  • 25
0

This is one way to solve it:

    // read file into list
    List<String> linesInFile = Files.readAllLines(Paths.get("filename.txt"));
    // create 2d array based on number of lines
    List<List<String>> array = new ArrayList<>(linesInFile.size());

    // iterate through every line of the file and split the elements using whitespace
    linesInFile.forEach(line -> {
        // get the elements in the current line
        String[] elements = line.split("\\s+");
        // store it in our 2d array
        array.add(Arrays.asList(elements));
    });

    // print every row in our 2d array
    array.forEach(System.out::println);

The Files.readAllLines method will return a List with all the lines in your file (similar to what your own version does).

Edit: Convert the List<List<String>> into ArrayList<ArrayList<String>> like following:

    ArrayList<ArrayList<String>> arrayList = new ArrayList<>();
    array.forEach(row -> arrayList.add(new ArrayList<>(row)));

    System.out.println(arrayList.getClass());
    System.out.println(arrayList.get(0).getClass());

Will output:

    >> class java.util.ArrayList
    >> class java.util.ArrayList
Selim
  • 1,064
  • 11
  • 23