java string.Substring StringIndexOutOfBoundsExcept

2019-07-16 14:10发布

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?

标签: java android
1条回答
仙女界的扛把子
2楼-- · 2019-07-16 14:26

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.

查看更多
登录 后发表回答