Unable to execute the program (no compilation error)

Dear experts,

I am doing my assignment on finding how many numbers in **N** digit satisfy **K** requirement.

However, when i am testing the code, i could compile it but i couldn't execute it.

I am wondering if i made mistake in the
Code :

x = result + y; // add them together and return it.

as when i comment this out, my program is able to execute,though i didn't get the right output value

Please kindly enlighten me.

Logic of my codes (example):

N = 15, K = 3

When N = 1, result = 0 + (N%10)

= 0 + (1%10)

= 1

y = N/10

= 1/10

= 0

x = 1 + 0

= 1

return x = 1

if (sumOfDigits(1) == K)

noOfNoSatisfy ++;

----------------------------------------------------

In the case of above, noOfSatisfy still remains as 0

-----------------------------------------------------

When N = 12, result = 0 + (N%10)

= 0 + (12%10)

= 2

y = N/10

= 12/10

= 1

x = 1 + 2

= 3

return x = 3

if (sumOfDigits(3) == K)

noOfNoSatisfy ++;

----------------------------------------------------

In the case of above, noOfSatisfy increase and plus 1

-----------------------------------------------------

Code :

import java.util.*;
public class Digits {
public static int sumOfDigits(int x) {
int result =0;
int y =0;
//eg. Let x be 1
while(x>0){
// eg. 1 = 1 + (1%10);
result = result + (x%10); //take the last digit of x
// eg. 0 = 1/10
y = x/10; //take the first digit of x
// eg. 1 = 1 + 0
x = result + y; // add them together and return it.
}
//eg. return 1
return x;
}
public static void main(String[] args) {
int N, K, noOfNoSatisfy;
Scanner sc = new Scanner (System.in);
//eg. Let N be 1
N = sc.nextInt();//indicate Number
//eg. Let K be 1
K = sc.nextInt();//indicate requirement number
noOfNoSatisfy = 0; // to count how many time it matches with K (requirement number)
for (int i = 1; i <=N; i++){
if(sumOfDigits(i) == K){//eg. 1 == K
noOfNoSatisfy ++; // plus 1 to count
}
} System.out.println(noOfNoSatisfy); //print the number of count
}
}

Re: Unable to execute the program (no compilation error)

Hello Alexie91,

I don't see where x would ever be less than 0 and thus you have an infinite loop. If the condition x>0 was to check if N was positive then I would suggest doing that before you even get to the loop. Really, this whole thing doesn't make much sense to me, if you can explain a little more about the assignment that may help.