i have started coding again in java after a few years of break and im trying to refresh up a bit now, but i seem to be struggeling to create a list of lists, not a multidimensional for example i just dump all my lists in one variable, if i need list x i fetch list x and assign that to a variable for easy access rather then looping through second dimension variabel.
this is what i currently have:
package src.handlers;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class TextManager {
public static void load_chapters(){
ArrayList sections = new ArrayList();
sections.add(read_lines("src\\chapters\\0.intro.txt"));
sections.add(read_lines("src\\chapters\\1.hello_world.txt"));
sections.add(read_lines("src\\chapters\\2.comments.txt"));
sections.add(read_lines("src\\chapters\\3.variabelen.txt"));
sections.add(read_lines("src\\chapters\\4.operators.txt"));
for(int x=0; x < sections.size(); x++){
// what i attempt to do ->
Object current_section = sections.get(x); // This gives object conversion error when assigning as List<String>
// loop here that loops all lines in current section.
// cannot access cause get function says its an object not a list?
System.out.println(current_section.get(3));
}
}
public static List<String> read_lines(String filename){
List<String> output = new ArrayList<String>();
// Probeer het bestand in te lezen.
try { // Maak buffereader aan voor het inlezen met filereader module.
BufferedReader read = new BufferedReader(new FileReader(filename));
String cur_line;
// zolang er een nieuwe lijn word gevonden en deze niet null is -> output toevoegen aan output variabel.
while((cur_line = read.readLine()) != null){
output.add(cur_line);
} // Sluiten van buffer reader voor exceptions te voorkomen / latere toegang mogelijk te maken.
read.close();
return output; //terugave vanalle file output.
}
catch(Exception e)
{
System.err.format("Exeption occured trying to read from '%s'.", filename);
e.printStackTrace();
return null;
}
}
}
got it thanks due alex :D
public static void load_chapters(){
ArrayList<List<String>> sections = new ArrayList();
sections.add(read_lines("src\\chapters\\0.intro.txt"));
sections.add(read_lines("src\\chapters\\1.hello_world.txt"));
sections.add(read_lines("src\\chapters\\2.comments.txt"));
sections.add(read_lines("src\\chapters\\3.variabelen.txt"));
sections.add(read_lines("src\\chapters\\4.operators.txt"));
for(List<String> section : sections){
for(String line : section){
System.out.println(line);
}
}
}
>`, you will have to know the index of the list in the parent list or you have to check its values. **Use a `Map>` for this**...
– deHaar Mar 09 '20 at 11:31