Java String with only digits or space ' '

Introduction

Checks if the String contains only unicode digits or space ' '.

A decimal point is not a unicode digit and returns false.

isNumeric(null)   = false
isNumeric("")     = true
isNumeric("  ")   = true
isNumeric("123")  = true
isNumeric("12 3") = true
isNumeric("ab2c") = false
isNumeric("12-3") = false
isNumeric("12.3") = false
public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "123 123";
        System.out.println(isNumericSpace(str));
    }/*  ww  w . j  a v a 2 s.  c o  m*/
    public static boolean isNumericSpace(String str) {
        if (str == null) {
            return false;
        }
        int sz = str.length();
        for (int i = 0; i < sz; i++) {
            if ((Character.isDigit(str.charAt(i)) == false) && (str.charAt(i) != ' ')) {
                return false;
            }
        }
        return true;
    }
}



PreviousNext

Related