Q: increment not working inside advanced for loop From the below method every time the line "System.out.println("J incremented to : "+j)" printed as 2. I dont know why. Pls anyone suggest me.
for(WebElement e : RefereceRange)
        {
            ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();",e);
            int j=1;
            if(e.isSelected())
            {
                e.click();
                j++;
                System.out.println("J incremented to : "+j);
            }
            if(j==size)
                break;
        }


A: I assigned j inside the for loop. so it assigned to 1 every time the loop continues. Now I declared j above for loop. It works

A: Your variable is inside loop, every time is born new.
Move before loop, ant rethink You want count from one or from zero
     int j=1; // maybe You want zero ???

     for(WebElement e : RefereceRange)
        {
            ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();",e);
            if(e.isSelected())
            {
                e.click();
                j++;
                System.out.println("J incremented to : "+j);
            }
            if(j==size)
                break;
        }


A: Your variable j is affected to 1 every time. If ou want to keep incrementing it, you have to instanciate it outside your loop.
int j=1;
for(WebElement e : RefereceRange)
    {
        ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();",e);

        if(e.isSelected())
        {
            e.click();
            j++;
            System.out.println("J incremented to : "+j);
        }
        if(j==size)
            break;
    }


A: I think you need to move the declaration of int j = 1 out of the loop, instead you say each time you loop « reset j to 1 », so with the increment, it will always print j as 2.
int j = 1;
for(WebElement e : RefereceRange) {
    ((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView();",e);

    if(e.isSelected()) {
        e.click();
        j++;
        System.out.println("J incremented to : "+j);
    }
    if(j==size)
        break;
}

