Solutions for Class 10 ICSE Logix Kips Computer Applications with BlueJ Java | IT Developer <?php echo $page_title; ?>
IT Developer

Conditional Constructs in Java

Chapter 8

Conditional Constructs in Java

Class 10 - Logix Kips ICSE Computer Applications with BlueJ


Share with a Friend

Java Program: Check Number of Digits


18. Create a program to find out if the number entered by the user is a two, three or four digits number.

Sample input: 1023
Sample output: 1023 is a 4 digit number.

import java.util.Scanner;

 

public class DigitCount {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

 

        // Input number

        System.out.print("Enter a number: ");

        int num = sc.nextInt();

 

        // Remove sign if number is negative

        int n = Math.abs(num);

 

        // Check number of digits

        if (n >= 10 && n <= 99) {

            System.out.println(num + " is a 2 digit number.");

        } else if (n >= 100 && n <= 999) {

            System.out.println(num + " is a 3 digit number.");

        } else if (n >= 1000 && n <= 9999) {

            System.out.println(num + " is a 4 digit number.");

        } else {

            System.out.println(num + " is not a 2, 3, or 4 digit number.");

        }

 

        sc.close();

    }

}

Output

Sample Input 
Enter a number: 1023

Sample Output 
1023 is a 4 digit number.

Explanation

  • The program reads an integer using the Scanner class.
  • Math.abs() is used to handle negative numbers.
  • The number is checked against numeric ranges:
    • 10–99 → 2 digits
    • 100–999 → 3 digits
    • 1000–9999 → 4 digits
  • An appropriate message is displayed.