Reputation: 1999
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
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
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
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
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
Reputation: 35
You could so something like
String numbers = "0123456789"
if(numbers.indexOf(roomNo.charAt(character)) >= 0)
...
Upvotes: 0
Reputation: 129587
Why not just do roomNo.matches("\\d+")
?
\d
matches any digit and, consequently, \d+
matches any string of only digits.
Upvotes: 4