2016-05-15 242 views
0

所以我有一些代码,调试Java for循环运行的次数太多

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循环运行了太多次,但无法弄清楚。我究竟做错了什么?

+0

为什么不简单地使用'digit/10'而不是'(int)Math.floor(digit/10)'? – MikeCAT

+0

另请注意,除了'digit> = getSize(source)'外,输入到'source'和循环计数器'i'的内容将不会返回到返回的内容:只有'digit'确定'digit < getSize(source)' – MikeCAT

+0

确保它在分割时不会四舍五入,但是因为您评论我认为它会自动舍入。 – Pyrrhic

回答

1

这是你的问题:

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

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

1

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