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?