java如何获取上一行arraylist的某个单元格

我有这样的数组列表


[111, 222, 333, 444, 555, 666, , ]

[1, 2, 3, 4, 5, 6, , ]

[11, 12, 13, 14, 15, 16, , ]

[a, s, d, f, g, h, , ]

我想检查它什么时候找到'h',它会检查第一个单元格的前一行是否等于'11'


到目前为止,我已经这样做了


DataFormatter formatter = new DataFormatter();


        String val = null;


        for (int rowNum = 0; rowNum < sheet.getLastRowNum() + 1; rowNum++) {

            Row r = sheet.getRow(rowNum);


            ArrayList<String> al = new ArrayList<String>();


            for (int i = 0; i <= r.getLastCellNum() + 1; i++) {

                Cell cell = r.getCell(i);

                val = formatter.formatCellValue(cell);

                al.add(val);

            }


for (int t = 0; t < al.size(); t++) {


    if (al.get(t).equals("h") && al.get(t + 1).equals("") && al.get(t + 2).equals("")) {


                    if (al.get(rowNum - 1) != null) {


                        if (al.get(rowNum - 1).contains("11")) {

                            System.out.println("valid");

                            continue;

                        } else {

                            System.out.println("invalid");

                            continue;

                        }

                    } else {

                        System.out.println("empty cell not exist ");

                        continue;

                    }

                }

            }

        }

输出 : invalid


输出:valid如果我也将“1”更改为“2”,但不是 3、4、5、6,则结果相同


有人可以向我解释一下吗?


摇曳的蔷薇
浏览 306回答 1
1回答

白猪掌柜的

首先你的数据结构不好。我建议你创建一个ArrayList<ArrayList<String>>来保存你的数据。将每一行放入一个 ArrayList,然后将 ArrayList 添加到主 ArrayList。现在数据结构和你上面提到的一样。或者您可以选择二元数组,例如String[][] arr = new String[10][];.您将行ArrayList<String> al = new ArrayList<String>();放入for loop, 意味着在每个循环中,您创建一个新的 ArrayList al,因此al每个循环中的数据都是空的。如果要al保留所有数据,则需要ArrayList<String> al = new ArrayList<String>();移出循环。对于您的代码,when(al.get(t).equals("h") && al.get(t + 1).equals("") && al.get(t + 2).equals(""))为 true,rowNum 为 3,al 为[a, s, d, f, g, h, , ]al.get(rowNum - 1) 为“d”。当(al.get(t).equals("16") && al.get(t + 1).equals("") && al.get(t + 2).equals(""))为真时,rowNum 为 2,al 为[11, 12, 13, 14, 15, 16, , ]al.get(rowNum -1) 为“12”。此外,您不al.get(rowNum - 1).contains("11")应该使用 ,al.get(rowNum - 1).equals("11")而应该使用。=================for (int t = 0; t < mainArrayList.size(); t++) {&nbsp; &nbsp; ArrayList<String> row = mainArrayList.get(t);&nbsp; &nbsp; for (int i = 0; i < row.size(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; if (row.get(i).equals("h") {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // your code&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}row是工作表的每一行。您需要循环每一行以检查每个字符串是否与“h”相等。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java