I wonder if it is possible to detect and/or stop infinite loop with basic java knowledge.
I got a school task(which considers our programming knowledge is on basic level) where we should take an input (int) from user and then take the sum of squares of the digits of that number (i.e. 123-->1^2+2^2+3^2). Then that result should be put in a while loop and it should repeat the same thing until it reaches 1 (i.e. 123-->1^2+2^2+3^2=14-->1^2+4^2=17-->1^2+7^2 etc)
If we get number 1 we should print "number is lucky!" and if it isn't it will be stuck in an infinite loop and we should print "number is not lucky!".
Now whats bugging me is how do they expect us to print "number is not lucky" if it will be stuck in an infinite loop ?
Is it possibly the badly written and designed task/question or there actually is a basic-level-knowledge way to detect and stop an infinite loop?
Here is my code(w/o the infinite loop detection):
import java.util.Scanner; public class Vezba { public static void main(String[] args) { boolean run = true; Scanner sc = new Scanner(System.in); int number = sc.nextInt(); int digits; int sum=0; int k = 10; int j = 1; while(run){ if(number<0){ run=false; } int len = String.valueOf(number).length(); /* Takes out each digit to make the first sum (probably redundant but please ignore)*/ while(len>0){ digits = number%k/j; j*=10; k*=10; len--; sum += digits*digits; } /* Repeats the process until sum is 1*/ while(sum>1){ int len2 = String.valueOf(sum).length(); int pom = 1; int k1=10; while(len2>0){ digits = sum%k1/pom; pom*=10; k1*=10; len2--; sum += digits*digits; } } System.out.println("Number is lucky!"); run=false; } } }