调试运行次数过多的java for循环

时间:2016-05-15 03:32:01

标签: java

所以我有一些代码,

public static int getNumberAtDigit(int source, int digit)
{
    if(digit > getSize(source))
        throw new IndexOutOfBoundsException(
                "There aren't " + String.valueOf(digit) + " digits in " + String.valueOf(source) + ".");
    else
    {
        // Remove digits that come after what we want
        for(int i = getSize(source); i > digit; i--)
            source = (int) Math.floor(digit / 10);
        //Narrow it to only the last digit and return it
        return source % 10;
    }
}

public static int getSize(long d)
{
    String numberS = String.valueOf(d);
    return numberS.length();
}

当我运行System.out.println(getNumberAtDigit(4532, 3));时,它返回0,但是当我运行System.out.println(getNumberAtDigit(4532, 4));时,它会返回2,就像它应该的那样。我已经测试并知道方法getSize(long d)不是罪魁祸首并且正常工作。我相信for循环运行的次数太多但无法弄清楚。我做错了什么?

2 个答案:

答案 0 :(得分:1)

应该是source = (int) Math.floor(source / 10);,而不是source = (int) Math.floor(digit / 10);,因为我并不关心digit / 10是什么。我很聪明:)

答案 1 :(得分:1)

这是你的问题:

source = (int) Math.floor(digit / 10);

如果digit的值小于10,则此函数将始终返回0.我相信您要做的是使用Math.floor(source / 10)

相关问题