Click here to Skip to main content
13,799,708 members
Rate this:
 
Please Sign up or sign in to vote.
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 14-May-18 5:56am
Updated 14-May-18 7:18am
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

Use a Regex: Lesson: Regular Expressions (The Java™ Tutorials > Essential Classes)[^]
Then it's trivial:
^\d+$
Is all the pattern you need.
  Permalink  
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.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Java gently provides the Character.isDigit[^] method. You may call it iteratively.
  Permalink  

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web06 | 2.8.181207.3 | Last Updated 14 May 2018
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100