drjava

How do I create an application that prompts the user for an integer and returns the number of digits it has?


I've started writing this code down, and I want to find the return of the number digits it has after the user prompts for the an integer. Where do I begin with this solution?

I'm still currently new to Dr Java coding. However, I've tried researching these methods, and I cannot find an example for this solution.

public class Recursion {
    public static void main(String[] args) { 
        Scanner input = new Scanner(System.in);
        System.out.println("Enter an integer.");
        int digit = input.nextInt();
        input.close();
    }
}

I expect it needs a recursion or method for this problem, and I believe it needs to return to the number digit, but I am not sure if it's correct.


Solution

  • you can use this function to count number of digits:

    function digits_count(n) {
          var count = 0;
          if (n >= 1) ++count;
    
          while (n / 10 >= 1) {
            n /= 10;
            ++count;
          }
    
      return count;
    }