Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I need to know if a String in Java, that it enters as a parameter, contains only numbers. I know that exists a method of String class, that let's you detect that.

What I have tried:

I tried to compare each character using Ascii code, conditionals and an ArrayList that contains each character of the String, but this solution is very inefficient.
Posted
Updated 14-May-18 6:18am

Use a Regex: Lesson: Regular Expressions (The Java™ Tutorials > Essential Classes)[^]
Then it's trivial:
^\d+$
Is all the pattern you need.
 
Share this answer
 
Comments
Jorge Echeverria Raddatz 14-May-18 11:47am    
Thanks for your help.
OriginalGriff 14-May-18 11:58am    
You're welcome!
CPallini 14-May-18 12:18pm    
5.
Java gently provides the Character.isDigit[^] method. You may call it iteratively.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900