简体   繁体   中英

Method to see if string contains ALL digits

I need to complete the method allDigits using isDigit that i wrote, that when passed a valid String, returns true if all characters of the String are digits, and false otherwise.

So far i have:

public static boolean isDigit (char ch){
    if (ch >= '0' && ch <= '9')
        return true;
    return false;
}

public static boolean allDigits(String s){
    for (int i =0; i<s.length(); i++)
        if(isDigit(s.charAt(i)) == true)
            return true;
    return false;
}

But this returns true if just say

public static void main(String[] args) {
    String s = "abc123";
    System.out.println(allDigits(s));
}

OUTPUT: true

However should return false

ALSO: Is my code efficient? I feel like theres an easier way. Any help is appreciated thanks

You should check each character and if it be not numeric, then return false, otherwise return true:

public static boolean allDigits(String s) {
    for (int i=0; i < s.length(); i++) {
        if (!isDigit(s.charAt(i)))
            return false;
    }

    return true;
}

But a cleaner way to handle this, and what I would do is to use a regex:

public static boolean allDigits(String s) {
    return s.replaceAll("\\d", "").equals("");
}

Note that the above method will treat an empty string as having all numeric characters. If you want empty string to fail, it would be easy to add this logic as an edge case.

I would always look for an already existing solution. How about using https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/StringUtils.html#isNumeric(java.lang.CharSequence) ?

I have confidence in these open source solutions concerning efficiency and correctness.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM