Вопрос

I'm having a problem in my code and I wondered if anyone could help me out.

//I'm looking from "?PARAMETER" in a text.
locatie = inhoud.indexOf("?");
inhoud = inhoud.substring(locatie);
lengte = inhoud.length();

//is this usefull to do?
inhoud = inhoud.trim();

//make string from question mark to next space
spatie = inhoud.indexOf(" ");
parameter = inhoud.substring(++locatie, spatie); //this line throws an error
System.out.println(parameter);

this code returns:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
ex out of range: -2
        at java.lang.String.substring(String.java:1911)
        at MailMatcher.personaliseren(MailMatcher.java:51)
        at MailMatcher.menu(MailMatcher.java:28)
        at MailMatcher.main(MailMatcher.java:61)

this is the input i use now:

text ?NAAM \n more text ?DAG some more

What i wish to do with my code for now is simply to echo the parameters in the console. I'm doing this for school; so I'm only requesting clarification for the error - I'll try to find the solution myself.

Это было полезно?

Решение

Your basic problem is because your first index you've found here:

locatie = inhoud.indexOf("?");

Then you make a substring and use this same index again here without changing it (except to increment which I guess is intended to exclude the question mark):

parameter = inhoud.substring(++locatie, spatie);

For the input string in your post what you end up with is this:

parameter = inhoud.substring(6, 5);

I think the exception (-2) is indicating the end index (4 since end index is exclusive) is 2 less than the begin index.

I think what you want is either

parameter = inhoud.substring(0, spatie);

or

parameter = inhoud.substring(1, spatie);

Depending on whether or not you want to exclude the question mark.

Also trimming removes trailing and leading whitespace. It's useful if that's something you need to do. In this scenario I'd say it's probably not useful. You've created the first substring based on a non-whitespace character so you can be sure there is not leading whitespace. With the second substring, the end index is exclusive so if you substring on whitespace you can also be sure there is no trailing whitespace.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top