I have a program that reads in a text file and will tokenize the words using a comma as a delimiter. It's working fine, but now I need to switch from using a 2-dimensional array where I know how many elements will be in it to using a 2-d ArrayList since I will not know how many elements will be passed into the ArrayList.
here's the working code with the multidimensional array, I'm really just looking for a way to change the below over to use an ArrayList so that i can pass in an unknown amount of elements to the array.
String filename = "input.txt";
File file = new File(filename);
Scanner sc = new Scanner(file);
arraySize = sc.nextLine().trim();
int size = Integer.parseInt(arraySize);
// creates a multidimensional array with the size set from the input file.
String[][] myArray = new String[size][];
// the outer for loop iterates through each line of the input file to populate the myArray.
for (int i = 0; i < myArray.length; i++) {
String line = sc.nextLine();
myArray[i] = line.split(","); //splits each comma separated element on the current line.
//the inner for loop gets each element of myArray and removes any white space.
for (int j = 0; j < myArray[i].length; j++) {
myArray[i][j] = myArray[i][j].trim();
}
}
this is what I've been working on, the only main difference is that the file will have spaces acting as the delimiter instead of commas. and also that it will read in an unkown number of elements from the file into the array. The add() method was giving me the below error.
The method add(int, List<String>) in the type List<List<String>> is not applicable for the arguments (String)
.
String filename = "input.txt";
File file = new File(filename);
Scanner sc = new Scanner(file);
// ArrayList<ArrayList<String>> myArray = new ArrayList<ArrayList<String>>();
List<List<String>> myArray = new ArrayList<>();
while(sc.hasNextLine()) {
String line = sc.nextLine(); // each line will have an equation
String[] equations = line.split("\\s+");
for (String s : equations) {
s = s.trim();
// myArray.add(s); can't figure out how to add into arraylist
}
}
sc.close();
edit: I'm not trying to pass an existing array to an ArrayList, just trying to find a way get a multidimensional ArrayList to hold an unspecified amount of elements that are read in from an input file, each word from the input file needs to be split using white space as a delimiter, and stored in the ArrayList.