Search code examples
javaarraystabular

How to print values in table using two different length of array


I want to create a table with two different arrays with different dimension but after executing it does not give me proper output.

I have below code:

String rowHeadingkeys[] = new String[] {"heading1","heading2","heading3","heading4","heading5","heading6","heading7","heading8"};
String rowValuekeys[] = new String[] {"Text1","Text2","Text3","Text4","Text5",
                                    "Text6","Text7","Text8","Text9","Text10",
                                    "Text11","Text12","Text13","Text14","Text15",
                                    "Text16","Text17","Text18","Text19","Text20",
                                    "Text21","Text22","Text23","Text24"};

    for(int i = 0;i<rowHeadingkeys.length;i++) {

        if(rowHeadingkeys!=null) {

            patientMonitoringTable.addCell(createCell(rowHeadingkeys[i],
                    PDFUtil.BOLD_FONT,1,Element.ALIGN_LEFT));

            for(int j = 0;j<rowValuekeys.length/rowHeadingkeys.length;j++) {

                patientMonitoringTable.addCell(createCell(svo.getFields().get(rowValuekeys[j]).getValue(),
                        PDFUtil.FONT,1,Element.ALIGN_LEFT));
            }

        }
}

and I want to make it like below:

| heading1 | Text1  | Text2  | Text3  |    
| heading2 | Text4  | Text5  | Text6  |    
| heading3 | Text7  | Text8  | Text9  |    
| heading4 | Text10 | Text12 | Text13 |    
| heading5 | Text14 | Text15 | Text16 |    
| heading6 | Text17 | Text18 | Text19 |    
| heading7 | Text20 | Text21 | Text22 |    
| heading8 | Text23 | Text24 | Text24 |

How to achieve this?


Solution

  • I'm guessing you're getting Text1 | Text2 | Text3 | for every heading.

    You shouldn't be assigning j = 0 in every loop. initialize an int index=0 outside of both for loops and the inner for loop should look like this.

    for(int j = index; j<index + (rowValuekeys.length/rowHeadingkeys.length);j++){
    
    }
    index+=rowValuekeys.length/rowHeadingkeys.length;
    

    Edit:

    a better solution would be:

    int innerIndex = 0;
    for(int i = 0;i<rowHeadingkeys.length;i++) {
    
        if(rowHeadingkeys!=null) {
    
            patientMonitoringTable.addCell(createCell(rowHeadingkeys[i],
                    PDFUtil.BOLD_FONT,1,Element.ALIGN_LEFT));
    
            for(int j = 0;j<rowValuekeys.length/rowHeadingkeys.length;j++) {
          if(innerIndex < rowValuekeys.length)
                patientMonitoringTable.addCell(createCell(svo.getFields().get(rowValuekeys[innerIndex]).getValue(),
                        PDFUtil.FONT,1,Element.ALIGN_LEFT));
               innerIndex++;
            }
    
        }
    

    }