Ad

Why Am I Getting StringIndexOutOfBoundsException Error In This Substring Method?

- 1 answer

protected Void doInBackground(Void... voids) {

...

ABV = elem.select("td > span.muted").text();
Log.d("myLOG_ABV", ABV);
Log.d("myLOG_ABVlength", String.valueOf(ABV.length()));

/*String temp_ABV = ABV.substring(ABV.length()-6, ABV.length());*/

... }

Result

D/myLOG_ABV: Russian River Brewing Company American Wild Ale | 7.50% D/myLOG_ABVlength: 55

and then, I cancled the annotation code.

...

ABV = elem.select("td > span.muted").text();
Log.d("myLOG_ABV", ABV);
Log.d("myLOG_ABVlength", String.valueOf(ABV.length()));

***String temp_ABV = ABV.substring(ABV.length()-6, ABV.length());***

...

Result

Caused by: java.lang.StringIndexOutOfBoundsException: length=0; index=-6

Why am I getting StringIndexOutOfBoundsException error in this substring method?

I got the result that 'ABVlength : 55' in my code with annotation.

But after cancellation of annotation, I got StringIndexOutOfBoundsException.

Seriously, I am fighting with this code for 7hours 30minutes.

Ad

Answer

So we have:

***String temp_ABV = ABV.substring(ABV.length()-6, ABV.length());***

Caused by: java.lang.StringIndexOutOfBoundsException: length=0; index=-6

How can you get an index of -6 in this situation? ABV must have zero length, i.e. "".

It may be the case that ABV should have at least six characters, but that indicates a bug elsewhere.

What to do?

First and foremost, validate your inputs.

Somewhere you would normally want something like:

if (abv.length() < 6) {
    throw new IllegalArgumentException("...");
}

Next find where that value is coming from and fix the bug.

Looks like you're parsing some kind of external document. In this case you may want the handling to be more lenient:

int abvLen = abv.length();
int abvEndIndex = abvLen - 6;
if (abvEndIndex < 0) {
    log.error("ABV length less than 6", abv);
    abvEndIndex = 0;
}
String abvEnd = abv.substring(abvEndIndex, abvLen);
Ad
source: stackoverflow.com
Ad