gpt4 book ai didi

java - 如何匹配 2 Arraylist 整数之间的行和单元格

转载 作者:行者123 更新时间:2023-11-30 10:09:12 24 4
gpt4 key购买 nike

我有两个数组列表。第一个数组列表 a1,包含行数,第二个数组列表 a2,包含像这样的单元格数:

enter image description here

我在这里要做的是尝试根据行数和单元格数设置颜色像这样存储在 a1 和 a2 中:

  a1: contain the current no of row that x located

a2: contain the current no of cell that x located

我试过这个:

for (int v3 : a1) {
for (int p3 : a2) {
XSSFRow BOFF = sheet.getRow(v3);
if (BOFF.getCell(p3) != null) {
BOFF.getCell(p3).setCellStyle(offcolor);
} else {
Cell cell1 = BOFF.createCell(p3);
cell1.setCellStyle(offcolor);
}
}
}

但结果不正确,与上图中红色突出显示的单元格相同。我试着在 a1 和 a2 之间切换,但结果也是一样的。任何人都知道如何做到这一点,以便它能正确地在 X 上着色?

更新:

这里我提供了如何将数据添加到数组列表中:

    ArrayList<Integer> a1= new ArrayList<Integer>();
ArrayList<Integer> a2= new ArrayList<Integer>();

下面是我如何搜索行和单元格

for (int i = 0; i < mainArrayList.size(); i++) {
ArrayList<String> row = mainArrayList.get(i);
for (int t = 0; t < row.size(); t++) {

if (row.get(t).equals("X")) {

a1.add(i);
a2.add(t);
continue;
}
}
}

更新:

当我运行我的代码时,结果如下:

enter image description here

最佳答案

原因

在给定的例子中,a1a2有8个元素,因此给定代码中的代码循环逻辑是

For each row having 'x' loop for each column having 'x', set the background color

至此第1,2,5-8行第0列和第2列的背景色设置完毕。

解决方案

为了快速修复,只需更改代码以循环 a1a2 中的每对元素。

for (int i = 0; i < a1.size(); i++) {
int rowIndex = a1.get(i);
int colIndex = a2.get(i);
XSSFRow BOFF = sheet.getRow(rowIndex);
if (BOFF.getCell(colIndex) != null) {
BOFF.getCell(colIndex).setCellStyle(offcolor);
} else {
Cell cell1 = BOFF.createCell(colIndex);
cell1.setCellStyle(offcolor);
}
}

但是,使用两个数组来存储坐标并不好,因为a1a2可能有不同的长度(由于程序错误),并导致意想不到的行为难以调试。

为了解决这个问题,我们可以使用 CellAddress POI 类并将代码重构为

for (CellAddress xCellAddress : xCellAddresses) {
XSSFRow BOFF = sheet.getRow(xCellAddress.getRow());
if (BOFF.getCell(xCellAddress.getColumn()) != null) {
BOFF.getCell(xCellAddress.getColumn()).setCellStyle(offcolor);
} else {
Cell cell1 = BOFF.createCell(xCellAddress.getColumn());
cell1.setCellStyle(offcolor);
}
}

哪个更具可读性,也更容易调试。

关于java - 如何匹配 2 Arraylist 整数之间的行和单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53367256/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com