This method checks if a String contains only numbers - Java java.lang

Java examples for java.lang:String Search

Description

This method checks if a String contains only numbers

Demo Code

/**/* w w  w .  ja  v a2 s  .  com*/
 * Copyright ? 2011 Mike Hershey (http://mikehershey.com | http://zcd.me) 
 * 
 * See the LICENSE file included with this project for full permissions. If you
 * did not receive a copy of the license email mikehershey32@gmail.com for a copy.
 * 
 * Among other restrictions you are not permitted to deploy this software for 
 * commercial purposes.
 */
//package com.java2s;

public class Main {
    /**
     * This method checks if a String contains only numbers
     */
    public static boolean containsOnlyNumbers(String str) {
        //It can't contain only numbers if it's null or empty...
        if (str == null || str.length() == 0) {
            return false;
        }

        for (int i = 0; i < str.length(); i++) {
            //If we find a non-digit character we return false.
            if (!Character.isDigit(str.charAt(i))) {
                return false;
            }
        }
        return true;
    }
}

Related Tutorials