title: Java program to check if number is happy yields an impossible output
body: <p>I've designed a program to input a number and check whether it is happy.</p>
  
  <pre><code>import java.util.*;
  
  public class isHappy
  {
  public static void main(String[] args)
  {
      Scanner sc = new Scanner(System.in);
  
      System.out.println("Enter number: ");
      int n = sc.nextInt();
  
      int l = String.valueOf(n).length();
      int temp=n;
  
      int midVar=0, addVar=0, i=0;
  
      while (temp!=4)
      {
          midVar=0;
  
          for (i=l; i&gt;0; i--)
          {
              addVar = temp/Math.pow(10, i);
              midVar+=Math.sqrt(addVar);
          }
  
          temp = midVar;
  
          if (temp==1)
            break;
      }
  
      if (temp==1)
      {
          System.out.println("Happy number");
      }
      else
      {
          System.out.println("Unhappy number");
      }
  }
  }
  </code></pre>
  
  <p>I do admit that the code I've used is not entirely clean, but it should work. And it certainly should not yield the output 2. Yes, that's it: After the user enters the number, the program just displays 2 in the next line. Let me walk you through the execution process.</p>
  
  <pre>Enter number:                                       //program output
  68                                                  //user input
  2                                                   //program output</pre>
  
  <p>I must add that I do in fact get a 'possible loss of precision' error during compilation, but I don't believe it actually might be a factor in the inexplicable output. Also, my main purpose in asking this question is not to get answers as to how to repair my code, but an explanation as to why I get the aforementioned strange output.</p>