2

Can someone explain fallowing? Here is code sample: Function is called with parameter: "S26V5"

private String uniqueCode(String inp) 
{
  String index = "023456789ABCDEFGHJKLMNOPQRSTUVWXYZ";
  int basse = index.length();
  String outt = "";
  inp = new StringBuilder(inp).reverse().toString();
  double oout = 0;
  int lenn = inp.length() - 1;
  Log.d("nom", "String inp lenght:" + Integer.toString(lenn));
    for (int i = 0; i <= lenn; i++)
    {
        double pow = Math.pow(basse, lenn - 1);
        Log.d("nom", "i=" + Integer.toString(i));
        Log.d("nom1",inp.substring(i, 1));
        Log.d("nom2", Integer.toString(index.lastIndexOf(inp.substring(i, 1))));
        oout += index.lastIndexOf(inp.substring(i, 1)) * pow;
    }
  outt = Double.toString(oout); //oout.ToString("F2");
  outt = outt.substring(0, outt.lastIndexOf('.'));
  outt = outt.substring(3);
  return outt;
}

Here is log from logcat:

nom(2597): String inp lenght:4 <- Ok, string lenght
nom(2597): i=0 <- first iteration
nom1(2597): 5 <- inp.substring(i, 1) first time
nom2(2597): 4 <- index.lastIndexOf(.... first time
nom(2597): i=1 <- second iteration and 
nom2(2597): 34 <- next is index.lastIndexOf(....
nom(2597): i=2
AndroidRuntime(2597): Shutting down VM
W/dalvikvm(2597): threadid=1: thread exiting with uncaught exception (group=0x409c01f8)
E/AndroidRuntime(2597): FATAL EXCEPTION: main
E/AndroidRuntime(2597): java.lang.StringIndexOutOfBoundsException: length=5; regionStart=2; regionLength=-1
E/AndroidRuntime(2597):     at java.lang.String.startEndAndLength(String.java:593)
E/AndroidRuntime(2597):     at java.lang.String.substring(String.java:1474)
E/AndroidRuntime(2597):     at Bar.Man.BarManActivity.uniqueCode(BarManActivity.java:750)

And question is: why in second iteration not printed inp.substring(i, 1) ? And i am constantly getting StringIndexOutOfBoundsException. Whats wrong with my code?

1 Answer 1

4

See substring(int beginIndex, int endIndex):

IndexOutOfBoundsException -

if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.

You'll fail in inp.substring(i, 1) when i > 1.

Sign up to request clarification or add additional context in comments.

3 Comments

I tried to convert my C# code. Now i see difference. In C# it is: public string Substring(int startIndex, int length). Is that function in java?
@Guntis substring in Java is substring(int startIndex, int endIndex)
@MarounMaroun, i already figured that out. Java does not have that function ? I just need to do that: inp.substring(i, **i+**1) ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.