That would work, but it doesn't look a very elegant solution. You can easily check the digits with
> '0' or
< '9', because if you look at this
Unicode/ASCII table, you will see that 0123456789 are consecutive. You will also see that I should have used ≤ and ≥ not > and <. You could also use “not”:-
!(c < '0' && c > '9').
Let's have a look at how you might do it with a Stream:-
This ’ is \u2019.
You can get an
IntStream from a String with its
chars() method (actually inherited from
CharSequence). That Stream goes through each
char as if cast to an
int. You can use its
allMatch() method which will stop execution whenever it hits a
false. Note the indentation: the .s align vertically.
The
IntPredicate required by allMatch is replaced by a
λ expression, in this case
testing whether the
int called
i is in the range 0...9.
Your technique will match the following text:-
0
0000000000000
00000000000001
1234567890
123456789012346789012345689012345678901234567890
and won't match
-1
-0
-1234567890
I would still prefer
or
Remember that a Scanner has these three methods:
1 2 3.
I am pretty sure some of this has been discussed earlier in the
thread or
here.
It all goes to show how useful old threads can be,