How to Check to See if a String Is Numeric with Java

The Java programming language contains support for a few primitive classes. Primitive classes include String for alphanumeric values, Integer for integer numbers, and Double for floating-point numbers. A String may contain any sequence of characters; in particular, some of those sequences (e.g., "-102") correspond to the decimal notation of a number. You can include code in your Java program to check if a string happens to denote a number.

Instructions

    • 1

      Check if the String denotes a valid integer by attempting to parse it as an Integer, as follows:

      Integer.parseInt(myString);

      Replace "myString" by the String variable you want to check in your code.

    • 2

      Catch the exception that the code in Step 1 will generate if the String happens to not denote a valid integer, by enclosing the code in Step 1 as follows:

      try

      {

      Integer.parseInt(myString);

      }

      catch (NumberFormatException exc)

      {

      System.out.println("Not a valid integer!");

      }

    • 3

      Check if the String denotes a valid floating-point number by attempting to parse it as an Double, as follows:

      Double.parseDouble(myString);

    • 4

      Catch the exception that the code in Step 1 will generate if the String happens to not denote a valid floating-point number, by enclosing the code in Step 3 as follows:

      try

      {

      Double.parseDouble(myString);

      }

      catch (NumberFormatException exc)

      {

      System.out.println("Not a valid floating-point number!");

      }

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured