Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string index out of range

 
Ann Ron
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 9256
9
Linux Mac OS X Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about checking that variable MessageLength and seeing how long of a String you've received?
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Raman Jha,
Your post was moved to a new topic.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic