Java - Write code to Checks if a string is a positive integer.

Requirements

Write code to Checks if a string is a positive integer.

Demo

public class Main{
    public static void main(String[] argv){
        String str = "book2s.com";
        System.out.println(isPositiveInteger(str));
    }//ww w .  j  a va  2  s.c  om
    /**
     * Checks if is positive integer.
     *
     * @param str
     *            the str
     * @return true, if is positive integer
     * @see <a href=
     *      "http://stackoverflow.com/questions/237159/whats-the-best-way-to-check-to-see-if-a-string-represents-an-integer-in-java">
     *      Stackoverflow question on faster options to Integer.parseInt()</a>
     */
    public static boolean isPositiveInteger(String str) {
        if (str.isEmpty())
            return false;

        if (str.charAt(0) == '-')
            return false;

        return StringHelper.isInteger(str);
    }
    /**
     * Checks if is integer.
     *
     * @param str
     *            the str
     * @return true, if is integer
     * @see <a href=
     *      "http://stackoverflow.com/questions/237159/whats-the-best-way-to-check-to-see-if-a-string-represents-an-integer-in-java">
     *      Stackoverflow question on faster options to Integer.parseInt()</a>
     */
    public static boolean isInteger(String str) {
        if (str.isEmpty())
            return false;

        int length = str.length(), i = 0;
        if (str.charAt(0) == '-') {
            if (length == 1) {
                return false;
            }
            i = 1;
        }
        for (; i < length; i++) {
            char c = str.charAt(i);
            if (c < '0' || c > '9') {
                if (c != '-') {
                    return false;
                }
            }
        }
        return true;
    }
}

Related Exercise