首页 > 解决方案 > 如何使用两个不同长度的数组在表中打印值

问题描述

我想创建一个包含两个不同维度的不同数组的表,但执行后它没有给我正确的输出。

我有以下代码:

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));
            }

        }
}

我想让它像下面这样:

| 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 |

如何做到这一点?

标签: javaarraystabular

解决方案


我猜你会得到 Text1 | 文本2 | 文本3 | 对于每个标题。

您不应该在每个循环中分配 j = 0 。在 for 循环之外初始化 int index=0,内部 for 循环应该如下所示。

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

}
index+=rowValuekeys.length/rowHeadingkeys.length;

编辑:

更好的解决方案是:

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++;
        }

    }

}


推荐阅读