Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Stringindexoutofboundsexception in android

 
achuthan mukundarajan
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to create a calculator app.IN order to avoid duplication of operators i am checking if the previous character in the string is an operator.But i am getting stringindexoutofboundsexception when i type in the third character.


For eg if i type "9+5-*" as the expression the * should replace the - sign.But even when i type 9+5 there is a stringoutofboundsexception when i type +.Please help!!

THe logcat


 
Ulf Dittmer
Rancher
Posts: 42969
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looks like the issue is in this line of code:

result.substring(result.length()-1).charAt(result.length()-1)

That makes sense, because the string resulting from the substring call is 1 character long (the error message confirms this), and you're using an index into based on the length of the original string. Since the string is 1 character long, the only valid index into it is "0" - the error message says you're using "2".

For debugging purposes, you may want to print out the value of "result" before calling any methods on it.
 
achuthan mukundarajan
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a way to fix the code . can you please post an alternative ?
 
Ulf Dittmer
Rancher
Posts: 42969
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Of course it can be fixed: don't index into a string using an index that's larger than the string length - 1. It seems that's what the code is doing, which indicates that your algorithm is wrong. I'm not sure what that particular piece of code is supposed to be doing, so I can't suggest how to do that (you are the expert on that, and should know what should happen :-)
 
achuthan mukundarajan
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am not so much of an expert here ;). The requirement is this : Suppose if i have a calculation string "9+5-3+.." and so on, and if i enter a operator('+','-','*','/') after the last + sign , it must be replaced ,not concatenated.
 
achuthan mukundarajan
Ranch Hand
Posts: 87
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I fixed it

sub=result.substring(result.length()-1);
value=sub.charAt(0);
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic