-1

I would like to find whether a string contains more than one number. I have two different statement, the first one which I wrote myself does what I want, but the second does not work. I am trying to figure the meaning of the second statement.

There is A:

    private static boolean moreThan2Num(String string) {
    int numberOfNumbers = 0;
    for (int i = 0; i < string.length(); i++) {
        if (Character.isDigit(string.charAt(i))) {
            numberOfNumbers++;
            if (numberOfNumbers > 1) {
                return true;
            }
        }
    }
    return false;
}

Here is B:

    static boolean moreThan2Num(String str) {
    for(int i=0;i<str.length();i++) {
        if(!Character.isDigit(str.charAt(i)))
            return false;
    }
    return true;
}

Here is my main:

    public static void main(String[] args) {
    String str1 = "as3as123aaag3";
    String str2 = "qweqweqwe";
    System.out.println(String.format("more then 4 number in \"%s\" - %s", str1, moreThan2Num(str1)));
    System.out.println(String.format("more then 4 number in \"%s\" - %s", str2, moreThan2Num(str2)));
    System.out.println(String.format("more then 4 number in \"%s\" - %s", str1, moreThan2Num1(str1)));
    System.out.println(String.format("more then 4 number in \"%s\" - %s", str2, moreThan2Num1(str2)));
}

I thought the second one should work, but it did not.

  • 1
    [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/q/25385173) – Andy Turner Aug 14 '19 at 12:50
  • in fact, the second method does not test if only digits present in a string. It tests if non-digits are *not* present: `moreThan2Num("")` -> true – Alex Salauyou Aug 14 '19 at 14:17

1 Answers1

5

In the second snippet you are returning false the first time you encounter a character that is not a digit. Therefore, you'll return false for any String that contains at least one character that is not a digit.

BTW, your first "moreThan2Num" method actually implements a logic that fits the name "atLeast2Num". If there are exactly two digits in the String, it will return true.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • True. The second statement will not go through the whole string and it returns false if there is an element which is not a digit. – user3741679 Aug 14 '19 at 13:00