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
Case 2: 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
Java program to check given character is digit or not
Please enter a character
Y
Given Character is Not Digit.
Explanation
Here, the output generated is “Given Character y is not a Digit” for input y (which is a character ), as the y>=’0’ and y<=’9’ , so both condition does not satisfy hence the else block of our program is executed.
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
java program to check given character is digit or not
Please enter a character
5
Given Character is Digit.
Explanation
In this case, the user inputs the input as 5, and the code generate the output as “The Given Character 5 is a Digit”, which shows the 5 is a numerical value, which is true. In the ‘condition’ block of our program, character.isdigit() returned true for character ‘5’. So the ‘if’ block executes and the desired output is generated.