Java - Write code to Check whether the given string represents a number.

Requirements

Write code to Check whether the given string represents a number.

Demo

/*
 * Copyright (c) 2001-2002, Marco Hunsicker. All rights reserved.
 *
 * This software is distributable under the BSD license. See the terms of the
 * BSD license in the documentation provided with this software.
 *//*from ww w  .j  a  v  a  2 s  .c  o  m*/
 
//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        System.out.println(isNumber(str));
    }

    /**
     * Checks whether the given string represents a number.
     *
     * @param str string to check.
     *
     * @return <code>true</code> if <em>str</em> represents a number.
     */
    public static boolean isNumber(String str) {
        if (str == null) {
            return false;
        }

        int letters = 0;

        for (int i = 0, size = str.length(); i < size; i++) {
            if ((str.charAt(i) < 48) || (str.charAt(i) > 57)) {
                letters++;
            }
        }

        if ((letters > 1) || ((letters == 1) && (str.length() == 1))) {
            return false;
        }

        return true;
    }
}