0

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

baked182
  • 45
  • 8
  • You are only checking if a digit exists. In order to check if all are digits, it is typically easier to check if none are digits and reverse the answer. – Thorbjørn Ravn Andersen Nov 12 '16 at 08:34
  • There is a good answer on how to achieve this [here](http://stackoverflow.com/questions/273141/regex-for-numbers-only). Hope it helps. – kingkeamo Nov 12 '16 at 08:36
  • Feel free to try the java regex, s.matches("^(\\d)*$") will return true if the String s only contains digits – M B Nov 12 '16 at 08:36
  • right now allDigits will return true as soon as isDigit returns true the first time. that is not what you want. – LiXie Nov 12 '16 at 08:37
  • 1
    Possible duplicate of [Java String - See if a string contains only numbers and not letters](http://stackoverflow.com/questions/10575624/java-string-see-if-a-string-contains-only-numbers-and-not-letters) – Alexei Levenkov Nov 12 '16 at 08:46
  • Does it matter if the string contains numerical values that are signed or contain decimal values such as "-1234" or "12345.678" ? Just curious. – DevilsHnd - 退職した Nov 12 '16 at 09:08

2 Answers2

1

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.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

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.