For validation purposes we might need to check if data entered by our users is a valid data for our application to process. A simple mechanism for checking if a character inputted is a digit or not can be done by using the java.lang.Character
class isDigit(char c)
method.
In this example you will learn how to check if a character representing a number. You will start by creating a string that contains some random alphanumeric characters in it. And then you are going to iterate these characters, get the value at the specific location using the charAt()
method. In the last section you are going to check to if the character represent a digit or not.
package org.kodejava.lang;
public class CharacterIsDigitExample {
public static void main(String[] args) {
// Manually creates a string with randoms characters.
String str = "12?XYZ4!6cba78+HI@0";
for (int i = 0; i < str.length(); i++) {
// Determines if the specified character is a digit
if (Character.isDigit(str.charAt(i))) {
System.out.println(str.charAt(i) + " is a digit.");
} else {
System.out.println(str.charAt(i) + " not a digit.");
}
}
}
}
These are the outputs of our program:
1 is a digit.
2 is a digit.
? not a digit.
X not a digit.
Y not a digit.
Z not a digit.
4 is a digit.
! not a digit.
6 is a digit.
c not a digit.
b not a digit.
a not a digit.
7 is a digit.
8 is a digit.
+ not a digit.
H not a digit.
I not a digit.
@ not a digit.
0 is a digit.
If there is a specific topic that picked your interest, you can turn to essay helper service (a professional writing service). It is a great alternative to classic googling. The experienced professionals will conduct extensive research on the topic for you and even write an essay if you need one.
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024