Java program to check a given character is a digit or not without using the built-in library method

Given/input a character, we have to check a given character is a digit or not without using the built-in library method.
Submitted by Nidhi, on February 24, 2022

Problem Solution:

In this program, we will read a character from the user and check the input character is a digit or not without using any built-in library method.

Program/Source Code:

The source code to check a given character is a digit or not without using the built-in method is given below. The given program is compiled and executed successfully.

// Java program to check a given character is a 
// digit or not without using the 
// built-in library method

import java.util.Scanner;

public class Main {
  static boolean isDigit(char ch) {
    if (ch >= '0' && ch <= '9')
      return true;
    return false;
  }

  public static void main(String[] args) {
    Scanner X = new Scanner(System.in);

    char ch = 0;

    System.out.printf("Enter character: ");
    ch = X.next().charAt(0);

    if (isDigit(ch))
      System.out.printf("Given character is a digit\n");
    else
      System.out.printf("Given character is not a digit\n");
  }
}

Output:

RUN 1:
Enter character: 8
Given character is a digit

RUN 2:
Enter character: R
Given character is not a digit

RUN 3:
Enter character: &
Given character is not a digit

Explanation:

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contains two static methods main() and isDigit().

The isDigit() method returns a Boolean value based on input character, it returns true if a given character is a digit otherwise it returns false.

The main() method is an entry point for the program. Here, we read a character from the user and checked input character is a digit or not and printed the appropriate message.

Java Basic Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.