为什么我在子字符串中出错?

时间:2014-08-28 15:48:38

标签: java android

可能是代码混乱,但我对Java的了解并不是很好。

我有以下功能,我在子字符串中出错,但我无法猜到原因。

private static void generateCode()
{       
    BigInteger basenumBig = BigInteger.valueOf(9007199254740989L);
    long basenum = basenumBig.longValue();

    StringBuilder index = new StringBuilder("abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ");

    long base = index.length();

    String out = new String();
    for (long t = (long) Math.floor(Math.log(basenum) / Math.log(base)); t >= 0; t--) {
        long bcp = (long) Math.pow(base, t);
        int a = (int) (Math.floor(basenum / bcp) % base);
        out = out + index.substring(a, 1);
        basenum = basenum - (a * bcp);
    }
    out = new StringBuilder(out).reverse().toString();

    System.out.println("CODE (" + out + ")");
}

结果应为" fE2XnNGpF"

2 个答案:

答案 0 :(得分:2)

您似乎正在使用substring函数作为(起始索引,长度),遗憾的是它不是在Java的字符串类中如何工作。从documentation开始,substring函数的两个参数是起始索引(包括)和结束索引(不包括)。因此,如果您想要从a开始的长度为1的子字符串:

index.substring(a, a+1);

具体来说,您当前的代码可能会抛出IndexOutOfBoundsException,因为有时beginIndex( a )大于endIndex( 1 )。

答案 1 :(得分:0)

您以错误的方式使用substring,输入为substring(start index, end index)。所以代码应该像

out = out + index.substring(1, a);