Jesse Luke Orange
Jesse Luke Orange

Reputation: 1999

How do I check if a String contains a numeric value

Hello basically I tried to use this code

    for(int character=0; character<roomNo.length(); character++){
        if((Character.isDigit(roomNo.charAt(character)))) {
        }
    }
    return true;

To loop through a String and see if it contains any numbers. I'm trying to create a method that checks whether a String is numeric, if it is the method should return true. So far it doesn't work? Any help would be appreciated :)

Upvotes: 2

Views: 4971

Answers (7)

case
case

Reputation: 124

I would suggest using NumberUtils from Apache Commons

Apache Commons isNumber(String)

Apache Commons isDigits(String)

Personal preference is to use a proven implementation rather than rolling my own.

Upvotes: 0

bellum
bellum

Reputation: 3710

You can check this using regexp:

roomNo.matches("\\d+");

Upvotes: 9

Patricia Shanahan
Patricia Shanahan

Reputation: 26185

The usual form of an explicit loop for this sort of validation is:

for each character in the string
  if not acceptable
    return false
return true

There are at least two alternatives that avoid an explicit loop, a regular expression (already suggested) and attempting conversion to the appropriate type in a try-catch.

For example, if you want an integer, call Integer.parseInt and catch NumberFormatException. If the exception happens, return false. If not, return true. The conversion strategy is especially useful for the more complicated formats, such as double.

Upvotes: 1

andreih
andreih

Reputation: 433

Try this:

    for(int character=0; character<roomNo.length(); character++){
    if(!Character.isDigit(roomNo.charAt(character))) {
         return false;
    }
}
return true;

Or as others have said, use regular expressions

Upvotes: 0

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

Since it's a room number, I'm assuming that you're looking for an Integer, so I'd recommend Integer.parseInt().

Upvotes: 1

turkycat
turkycat

Reputation: 35

You could so something like

String numbers = "0123456789"
if(numbers.indexOf(roomNo.charAt(character)) >= 0)
...

Upvotes: 0

arshajii
arshajii

Reputation: 129587

Why not just do roomNo.matches("\\d+")?

\d matches any digit and, consequently, \d+ matches any string of only digits.

Upvotes: 4

Related Questions