2

有人可以解释休耕吗?这是代码示例:函数调用参数:“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;
}

这是来自 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)

问题是:为什么在第二次迭代中没有打印inp.substring(i, 1)?我不断得到StringIndexOutOfBoundsException。我的代码有什么问题?

4

1 回答 1

4

substring(int beginIndex, int endIndex)

IndexOutOfBoundsException -

如果 beginIndex 为负数,或者 endIndex 大于此 String 对象的长度,或者 beginIndex 大于 endIndex

你会在inp.substring(i, 1)什么时候失败i > 1

于 2013-11-11T16:09:50.027 回答