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 ();

      try
    {

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

Related Java Snippets

Last modified: July 13, 2019

Comments

Write a Reply or Comment

Your email address will not be published.