Doge Overlord Doge Overlord - 5 months ago 8x
Java Question

Debugging java for loop that runs too many times

So I have some code,

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) + ".");
// 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();

and when I run
System.out.println(getNumberAtDigit(4532, 3));
it returns 0 but when I run
System.out.println(getNumberAtDigit(4532, 4));
it returns 2, like it should. I have tested and know that the method
getSize(long d)
isn't the culprit and works as normal. I believe the for loop is running too many times but cannot figure it out. What am I doing wrong?


Here's your problem:

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

If the value of digit is less than 10, this function will always return 0. I believe what you meant to do is use Math.floor(source / 10).