Java program to check if a string is numeric
Here's an example Java program to check if a string is numeric:
public class NumericChecker { public static void main(String[] args) { String str = "12345"; if (isNumeric(str)) { System.out.println("The string is numeric"); } else { System.out.println("The string is not numeric"); } } public static boolean isNumeric(String str) { try { Double.parseDouble(str); return true; } catch (NumberFormatException e) { return false; } } }
This program uses an isNumeric
method that takes a string as input and returns true
if the string is numeric, and false
otherwise.
To check if the string is numeric, the isNumeric
method attempts to parse the string as a double using the Double.parseDouble
method. If the parse operation succeeds, the method returns true
, indicating that the string is numeric. If the parse operation throws a NumberFormatException
, the method returns false
, indicating that the string is not numeric.
In the main method, the isNumeric
method is called with a sample string "12345"
. If the string is numeric, the program prints a message indicating that the string is numeric. Otherwise, it prints a message indicating that the string is not numeric.