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

调试运行次数过多的java for循环,java,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) + ".

所以我有一些代码

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(longd)
不是罪魁祸首,正常工作。我相信for循环运行的次数太多了,但无法理解。我做错了什么?

应该是
source=(int)Math.floor(source/10),而不是
源=(int)数学地板(数字/10)应该是
source=(int)Math.floor(source/10),而不是
源=(int)数学地板(数字/10)这是你的问题:

source = (int) Math.floor(digit / 10);
如果数字
的值小于10,此函数将始终返回0。我相信你想做的是使用
Math.floor(source/10)

这是你的问题:

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

如果数字
的值小于10,此函数将始终返回0。我相信你的意思是使用
Math.floor(source/10)

为什么不简单地使用
digit/10
而不是
(int)Math.floor(digit/10)
?还要注意,输入到
source
的内容和循环计数器
I
不会对返回的内容产生影响,除非
digit>=getSize(source)
:只有
digit
确定为
digit
返回的值,以确保它在除法时不会向上取整,但因为您评论说,我假设它会自动向下取整。如果
digit>getSize(source)
然后它抛出
索引自动边界异常
,如果
digit==getSize(source)
那么代码应该有效,为什么不直接使用
digit/10
而不是
(int)Math.floor(digit/10)
?还要注意,输入到
source
的内容和循环计数器
i
不会对返回的内容产生影响,除非
digit>=getSize(source)
:只有
digit
确定
digit
返回的内容,以确保它在除法时不会取整,但是既然你评论了,我假设它会自动取整。如果
digit>getSize(source)
,那么它会抛出
IndexOutOfBoundsException
,如果
digit==getSize(source)
,那么代码应该并且确实有效