J Mullen J Mullen - 5 months ago 10
Java Question

Printing pattern from list in Java

What I have done here is taken the contents of the table below and stored them in a list called

tableElems


0 1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16 17
18 19 20 21 22 23 24 25 26
27 28 29 30 31 32 33 34 35

List<WebElement> tableElems = chrome.findElements(By.tagName("td"));


From this table I want to print in a pattern starting at the 4th element (#3 in the table) and I want to print 3 elements, then skip the next 6, print the next 3 and then skip the next 6, etc. etc.

So my expected output would be
3 4 5 12 13 14 21 22 23 30 31 32


My initial attempt ended with

for (int i = 3; i<tableElems.size(); i++) {
if(i % 3 == 0) { System.out.println(tableElems.get(i).getText()); }
else if(i % 4 == 0) { System.out.println(tableElems.get(i).getText()); }
else if(i % 5 == 0) { System.out.println(tableElems.get(i).getText()); }
}


Obviously this is wrong, because my
% 3
will print the 9th element,
% 4
will print the 16th element, etc.

I am having trouble wrapping my head around this, so any advice to point me in the right direction is appreciated!

Answer

If you want to stick to %, then this should work

int rowSize = 9;
for (int i = 0; i < tableElems.size(); i++) {

    int column = i % rowSize;

    if (column >=3 && column <= 5) {
        System.out.println(tableElems.get(i).getText());
    }
}