0

Sorry for this question, I understand, for somebody this is easy, but I need help

For example I have:

@FindBy(xpath="example")
private List<WebElement> exampleList;

And I need to click on the random item in the list:

public void clickOnRandomItemInList() {
    exampleList.get(i).click; //how I can randomize "I"
}

I tried this one:

Random randomize = new Random()
public void clickOnRandomItemInList() {
    exampleList.get(randomize.nextInt(exampleList.size)).click; //but this way doesn't work
}

2 Answers 2

1

You can do it as following:
Get a random index according to the List size, get element from the List accordingly and click it.

public void clickOnRandomItemInList(){
    Random rnd = new Random();
    int i = rnd.nextInt(exampleList.size());
    exampleList.get(i).click();
}
Sign up to request clarification or add additional context in comments.

Comments

1

We need to determine lower limit and upper limit and then generate a number in between.

lower limit we will set to 1, cause we at least wanna deal with 1 web element.

upper limit we will use list size, int high = exampleList.size();

Now using the below code

Random r = new Random();
int low = 1;
int high = exampleList.size();
int result = r.nextInt(high-low) + low;

and now call this method

public void clickOnRandomItemInList() {
    Random r = new Random();
    int low = 1;
    int high = exampleList.size();
    int result = r.nextInt(high-low) + low;
    exampleList.get(result).click; 
}

PS low is (inclusive) and high is (exclusive)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.