I am making a program to learn how to manage text strings and files in Java, where the user will enter university modules in blocks of time. It's still a prototype, and for now I'm trying to fill an array of StringBuilders with the base structure, so I can then mutate it with the data the user enters.
My method was to create an empty StringBuilder array, of dimension 6X10, fill it with empty strings, and then "fill" it with an array of Strings with the basic structure:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
StringBuilder[][] baseStructure = new StringBuilder[6][10];
for(int i = 0; i < 6; i++){
for(int j = 0; j < 10; j++){
baseStructure[i][j] = new StringBuilder();
}
}
String[][] baseStructure2 = {
{"HORA", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes"},
{" 8:30 - 9:30", "1", "2", "3", "4", "5"},
{" 9:40 - 10:40", "1", "2", "3", "4", "5"},
{"10:50 - 11:50", "1", "2", "3", "4", "5"},
{"12:00 - 13:00", "1", "2", "3", "4", "5"},
{"13:10 - 14:10", "1", "2", "3", "4", "5"},
{"14:20 - 15:20", "1", "2", "3", "4", "5"},
{"15:30 - 16:30", "1", "2", "3", "4", "5"},
{"16:40 - 17:40", "1", "2", "3", "4", "5"},
{"17:50 - 18:50", "1", "2", "3", "4", "5"}
};
for(int m = 0; m < 6; m++){
for(int n = 0; n < 10; n++){
printMatrix(baseStructure);
baseStructure[m][n] = new StringBuilder(baseStructure2[m][n]);
}
}
}
public static void printMatrix(StringBuilder[][] strMatrix){
for (StringBuilder[] strings : strMatrix) {
System.out.println(Arrays.deepToString(strings));
}
}
However, even though my loops have the same dimension values, when running the program I get index access errors out of range 6.
WHAT I TRIED:
I tried to populate a StringBuilder matrix, "copying" data from a String matrix, printing it as the loop went to see it grow with each iteration.
The program works until it reaches the end of the first row, where it manages to copy the data until the Friday, and then breaks:
[HORA, Lunes, Martes, Miercoles, Jueves, Viernes, , , , ]
[, , , , , , , , , ]
[, , , , , , , , , ]
[, , , , , , , , , ]
[, , , , , , , , , ]
[, , , , , , , , , ]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for length 6 at Main.main(Main.java:44)
I can tell there's something wonky because the first row should NOT have 4 extra empty spaces, but I'm not sure what's causing it.
(Developed on Java 23.0.1 on IntellliJ IDEA Community Edition 2024.3.1.1)
It seems like you inverted the dimensions of your 2d array. Which also reflected in both your loops. You have 10 lines who each have 6 elements per line, not the other way round. :)
The 2d array, instead of 6, 10:
StringBuilder[][] baseStructure = new StringBuilder[10][6];
Loop 1:
for(int i = 0; i < 10; i++){
for(int j = 0; j < 6; j++){
And loop 2:
for(int m = 0; m < 10; m++){
for(int n = 0; n < 6; n++){