Click here to Skip to main content
13,899,599 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.
Updated 14-May-18 6:18am
Rate this: bad
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:
Is all the pattern you need.
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
Rate this: bad
Please Sign up or sign in to vote.

Solution 2

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

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.190306.1 | Last Updated 14 May 2018
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

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