Advertisement
newbninja

Question 3.1

Oct 16th, 2023
532
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class DigitCount {
  4.     public static void main(String[] args) {
  5.         // Create a Scanner object to read input from the user
  6.         Scanner scanner = new Scanner(System.in);
  7.  
  8.         // Prompt the user to enter a positive integer
  9.         System.out.print("Enter a positive integer less than 10,000,000,000: ");
  10.  
  11.         // Read the integer from the user
  12.         long number = scanner.nextLong();
  13.  
  14.         // Close the Scanner
  15.         scanner.close();
  16.  
  17.         // Check if the input number is within the valid range
  18.         if (number < 1 || number >= 10000000000L) {
  19.             System.out.println("Invalid input. Please enter a positive integer less than 10,000,000,000.");
  20.         } else {
  21.             // Calculate the number of digits using a loop
  22.             int digitCount = 0;
  23.             while (number > 0) {
  24.                 number /= 10; // Remove the rightmost digit
  25.                 digitCount++; // Increment the digit count
  26.             }
  27.  
  28.             // Display the result
  29.             System.out.println("The number of digits in the input is: " + digitCount);
  30.         }
  31.     }
  32. }
  33.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement