Check if string contains valid number - Java Language Basics

Java examples for Language Basics:Number Parse

Description

Check if string contains valid number

Demo Code


public class Main {

  public static void main(String[] args) {

    String[] str = new String[] { "10.20", "1234.56", "12.invalid","1.1.1" };

    for (int i = 0; i < str.length; i++) {

      if (str[i].indexOf(".") > 0) {

        try {/*from  w ww .ja  v  a 2 s  .  c om*/
          Double.parseDouble(str[i]);
          System.out.println(str[i] + " is a valid decimal number");
        } catch (NumberFormatException nme) {
          System.out.println(str[i] + " is not a valid decimal number");
        }

      } else {
        try {
          Integer.parseInt(str[i]);
          System.out.println(str[i] + " is valid integer number");
        } catch (NumberFormatException nme) {
          System.out.println(str[i] + " is not a valid integer number");
        }
      }
    }

  }
}

Result


Related Tutorials