In this tutorial we are going to check if the character is Digit ( 0-9) and write the java program for the same. There are some logic behind characters which are mentioned below:
- A character is said to be Alphabet, if it lie between ‘a’ to ‘z’ or ‘A’ to ‘Z’.
- A character is said to be Digit, if it lie between 0-9.
- A character is said to be Special Symbol, if it is neither Digits nor Alphabet.
For the any input character our program will check either character is vowel or consonant.
For example
Case 1: If user is given input 1
Output should be “Digit”
As we know that 1 is digit
Case2: If user is given b or B
Output should be “Not a Digit”
As we know that B is a Alphabet not a digit.
Program 1: Java Program to check given input is Digit or not
import java.util.*;
public class Main
{
public static void main (String[] args)
{
System.out.println("Java program to check given character is digit or not");
Scanner sc = new Scanner (System.in);
System.out.println ("Please enter a character");
char ch = sc.next ().charAt (0);
if(ch>='0' && ch<='9')
{
System.out.println("Given Character is Digit.");
}
else
{
System.out.println("Given Character is Not Digit.");
}
}
}
Output
Explanation
The Java program uses a Scanner
object to prompt the user for a single character input and then checks if the character is a digit. It begins by printing an introductory message. The program then reads the first character of the user’s input. Using a conditional statement (if
–else
), it checks whether the character falls within the ASCII range for digits (‘0’ to ‘9’). If the character is a digit, it prints “Given Character is Digit.”; otherwise, it prints “Given Character is Not Digit.” This is a simple yet effective way to differentiate between digit and non-digit characters based on their ASCII values.
Program 2 : Program to check input is Digit or not in Java
import java.util.*;
public class Main
{
public static void main (String[] args)
{
System.out.println("java program to check given character is digit or not");
Scanner sc = new Scanner (System.in);
System.out.println ("Please enter a character");
char ch = sc.next ().charAt (0);
if(Character.isDigit(ch))
{
System.out.println("Given Character is Digit.");
}
else
{
System.out.println("Given Character is Not Digit.");
}
}
}
Output
Explanation
This Java program determines whether a character entered by the user is a digit. It uses the Scanner
class from the java.util
package to read input from the console. After prompting the user to enter a character, it retrieves the first character of the input. The program then uses the Character.isDigit
method to check if this character is a digit. If it is, the program outputs “Given Character is Digit.” Otherwise, it outputs “Given Character is Not Digit.” This approach effectively leverages a built-in method to simplify the digit-checking process, making the code more readable and robust against incorrect inputs.