1. Introduction
In Java, we often need to check if a given string is numeric. A numeric string contains only digits and possibly a decimal point, making it a valid representation of a number. In this blog post, we will develop a Java program to verify whether a given string is numeric.
2. Program Steps
1. Define a main method as the starting point of the program.
2. Initialize a few strings, both numeric and non-numeric, for testing.
3. Call a method isNumeric for each string to check if it is numeric.
4. In the isNumeric method, use regular expressions to check if the string is a valid number.
5. Print the results for each string.
3. Code Program
public class NumericStringCheck {
public static void main(String[] args) {
// Step 2: Initialize strings for testing
String test1 = "12345";
String test2 = "123.45";
String test3 = "123a45";
// Step 3: Call the isNumeric method and print results
System.out.println(test1 + " is numeric: " + isNumeric(test1));
System.out.println(test2 + " is numeric: " + isNumeric(test2));
System.out.println(test3 + " is numeric: " + isNumeric(test3));
}
public static boolean isNumeric(String str) {
// Step 4: Use regular expression to check if the string is a valid number
return str.matches("[-+]?\\d*\\.?\\d+");
}
}
Output:
12345 is numeric: true 123.45 is numeric: true 123a45 is numeric: false
4. Step By Step Explanation
– Step 1: We define the main method, which serves as the starting point of our program.
– Step 2: Three strings test1, test2, and test3 are initialized for testing purposes.
– Step 3: The isNumeric method is invoked for each test string, and the results are printed to the console.
– Step 4: Inside the isNumeric method, we use a regular expression to check if the string is a valid number. The method returns true if the string is numeric, otherwise false.
– Step 5: The output shows whether each test string is numeric or not.
By following these steps, we can efficiently determine whether a given string in Java is numeric using regular expressions.