Strings
Java Program to Check if String is Numeric
A Java program to check if a string contains only numeric characters.
Problem Description
Write a Java program to check if a given string is numeric (contains a valid number).
Code
public class CheckNumeric {
public static void main(String[] args) {
String string = "12345.15";
boolean numeric = true;
try {
Double num = Double.parseDouble(string);
} catch (NumberFormatException e) {
numeric = false;
}
if(numeric)
System.out.println(string + " is a number");
else
System.out.println(string + " is not a number");
}
}Output
12345.15 is a numberExplanation
Double.parseDouble(): Attempts to convert the string to a double.NumberFormatException: Thrown if the string is not a valid number.- Try-Catch: Used to handle the exception and determine validity.
