| Author |
string index out of range
|
Ann Ron
Greenhorn
Joined: Oct 21, 2003
Posts: 24
|
|
Hi, I am writing this code and getting an error : java.lang.StringIndexOutOfBoundsException: String index out of range: -70 This is my code snippet,Any idea how I solve this one.. ************************************************************ String outstring = "123"; String repid; String incno; int MessageLength = MQ_Message.getMessageLength( ); outString = MQ_Message.readString(MessageLength); repid = outString.substring(83,13); incno = outString.substring(96,9); ************************************************** Thanks in advance Ann
|
 |
Joe Ess
Bartender
Joined: Oct 29, 2001
Posts: 8265
|
|
|
How about checking that variable MessageLength and seeing how long of a String you've received?
|
"blabbing like a narcissistic fool with a superiority complex" ~ N.A.
[How To Ask Questions On JavaRanch]
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24059
|
|
You wrote
repid = outString.substring(83,13); incno = outString.substring(96,9);
The two arguments to substring are the first (inclusive) and last (exclusive) character to include; it looks like you're assuming the second argument is a count, which it's not. This and many other methods are documented in the online API Javadocs -- learn to use them, they'll save you a lot of trouble! Now, beyond just the technical, and on to the stylistic: you've got a number "messageLength" which is the unknown length of a message. But your code is assuming that it will always be greater than 105. You might want to explicitly test that, and handle the error case where it's not. Just a thought -- otherwise, you'll soon be asking us about another mystery exception!
|
[Jess in Action][AskingGoodQuestions]
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3795
|
|
Raman Jha, Your post was moved to a new topic.
|
 |
 |
|
|
subject: string index out of range
|
|
|