2
WebElement ELR = driver.findElement(By.id("trades-list"));
List<WebElement> list = driver.findElements(
  By.xpath("//*[contains(@id,'trade-summary-92')]")
);

String[] tradeId = null; 
for(int i = 0; i < list.size(); i++ )
{
    String str = list.get(i).getAttribute("id");
    tradeId[i] = str.substring(23);
    System.out.println(tradeId[i]);
}

str will contain following list is the output of String str = list.get(i).getAttribute("id");

trade-summary-92222
trade-summary-93333
trade-summary-94444

Here I want to print 92222, 93333, 94444 in the string tradeId.

I am getting the following error message:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -4 at java.lang.String.substring(Unknown Source) at com.traderev.selenium.multipleBrowser.main(multipleBrowser.java:71)

1
  • Glad to have helped. If your question is solved, you should accept Niels' answer. It answers the original question of copying substrings very nicely. Apr 23, 2015 at 18:04

2 Answers 2

3

How do you come to 23 in tradeId[i] = str.substring(23);, your strings like trade-summary-92222 are only 19 characters long, not?

19 - 23 = -4, which is what your errors says its can't find the last 4 characters.

For readability and a partial string you could use: public String substring(int beginIndex, int endIndex)

Your code would become:

tradeId[i] = str.substring(19-5, 19);

Or try just this to get the last five

tradeId[i] = str.substring(str.length() - 5);

Or to prevent the exception if the string becomes shorter then 5

tradeId[i] = str.substring(Math.max(0, text.length()-5)); 

Or this

tradeId[i] = str.substring(s.lastIndexOf('-') + 1);
1
  • I tried the above method but now getting exception as Total count is3 trade-summary-92195 Exception in thread "main" java.lang.NullPointerException at com.traderev.selenium.multipleBrowser.main(multipleBrowser.java:73)
    – Monika
    Apr 21, 2015 at 14:05
2

You are getting a nullpointer exception because you're trying to assign values to index locations in a null array.

This statement

String[] tradeId = null; 

should be

String[] tradeId = new String[list.size()]; 

so when you later do this:

tradeId[i] = str.substring(s.lastIndexOf('-') + 1);

There will be a space in the array reserved for that value.

Hope that helps!

0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.