Check if a Number is valid using Java

Below is a snippet to check if a number  is valid or not. For example, the string “1.1.1” contains an invalid number, while the string “2.1” contains a valid number.

The Code

public class Main

  public static void main (String[]args)
    int i;
     System.out.println("Enter a Number:");
    String str = System.console().readLine ();


      System.out.println(str + " is a valid number");
    } catch (NumberFormatException ex)
      System.out.println(str + " is not a valid number");

Related Java Snippets

Asha Shoukeir

About Asha shoukeir

Software Developer and System Administrator

View all posts by Asha shoukeir →

Leave a Reply