jQuery in Action, 3rd edition
The moose likes Java in General and the fly likes string index out of range Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "string index out of range" Watch "string index out of range" New topic

string index out of range

Ann Ron

Joined: Oct 21, 2003
Posts: 24
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
Joe Ess

Joined: Oct 29, 2001
Posts: 9189

How about checking that variable MessageLength and seeing how long of a String you've received?

[How To Ask Questions On JavaRanch]
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

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

Joined: Apr 06, 2010
Posts: 4544

Raman Jha,
Your post was moved to a new topic.
I agree. Here's the link: http://aspose.com/file-tools
subject: string index out of range
It's not a secret anymore!