Selenium and Java: While loop not working as expected

Wade Byron Profe :

I have a challenge with automating a click action and I'm struggling to understand what's wrong with the logic in my solution.

My challenge is that I need to click one of a number of different radio buttons.

Each radio button has an id of "r" + a_number.

I don't know, for any given test, what the available "r" + a_number options there will be, so I wrote this while loop, which is intended to click the first available radio button:

int counter = 0;

while(true) {
    counter++;
    try {
        driver.findElement(By.id("r" + counter)).click();
    } catch (NoSuchElementException e) {
        continue;
    }

    break;

}

This isn't working as intended - could someone help me understand what's wrong?

Note: I'm a novice with Java

Update

My aim is to click the first existing radio button, so the while loop increments the counter var, let's say r=1, then attempts to click a radio button with id "r1". If there is no such element with id "r1", a NoSuchElementException is thrown, in which case the current while loop iteration should stop and start the next iteration (r = 2, try to click element "r2", if does not exist, start next while loop cycle).

Suppose we get to element "r20" and this element does in fact exist, then the button should be clicked, the exception is not thrown and so the while loop continues and hits the break command, and the while loop is terminated.

The current behaviour, however, is that the exception does not get handled even when the element does not exist, the while loop terminates, but nothing has been clicked.`

Ashish :

There are two issues with the code:

  1. Loop running only once- You are breaking the loop using break statement, after the first iteration itself.

  2. No exception thrown- You are not logging the exception. You are only executing a 'continue' statement in the catch block. You do not need the statement because the loop will go to next iteration anyway (well after you remove the break statement).

You should use this code:

int counter = 0;
boolean foundElement = false;
while(!foundElement) {
    counter++;
    try {
        driver.findElement(By.id("r" + counter)).click();
        foundElement = true;
    } catch (NoSuchElementException e) {
       //assuming you want to log exception. Otherwise you can leave the catch block empty.
       System.out.println(e);     
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=171040&siteId=1