September 2019
Intermediate to advanced
816 pages
18h 47m
English
The solution to this problem relies on the Character.isDigit() or String.matches() method.
The solution relying on Character.isDigit() is pretty simple and fast—loop the string characters and break the loop if this method returns false:
public static boolean containsOnlyDigits(String str) { for (int i = 0; i < str.length(); i++) { if (!Character.isDigit(str.charAt(i))) { return false; } } return true;}
In Java 8 functional style, the preceding code can be rewritten using anyMatch():
public static boolean containsOnlyDigits(String str) { return !str.chars() .anyMatch(n -> !Character.isDigit(n));}
Another solution relies on String.matches(). This method returns a boolean value indicating whether ...
Read now
Unlock full access