Win a copy of Functional Reactive Programming this week in the Other Languages forum!

# Check to see if it's a number or not

Rocky Summers
Ranch Hand
Posts: 66
hello ranchers,
i'd like to know how to get a string and check to see if it's a bunch of numbers or not..
~ rockster

Marilyn de Queiroz
Sheriff
Posts: 9067
12
static boolean isDigit(char ch)
Determines if the specified character is a digit.

Dirk Schreckmann
Sheriff
Posts: 7023
And then you'll likely find the length() and charAt(int) methods of the String class to be useful.

Jim Yingst
Wanderer
Sheriff
Posts: 18671
Beware that you might need to clarify just what kind of numbers you need to consider. What about the following?
-1
+1
1.0
0.1
.1
1E5
1.23e5
12,345
123456879012 (too big for int)
123456879012345678901234567890 (too big for long)
01
0x7F3A
Your problem will be much simpler if you decide you don't need to handle these cases. Or if you at least limit the number of cases you need to handle. But it may be that you are required to handle some of these cases, in which case, don't overlook them. If you do need more here, it's probably not really a Beginner-level problem anymore, so let us know if that's the case and we can move this post to another forum.

Rocky Summers
Ranch Hand
Posts: 66
holy crow i didnt know it'd be that complex.. thought i was dealing with a problem here with a really easy answer that i just couldn't figure out.
what i'm actually dealing here is we're doing error checking to see if the user has inputted a valid info: in the fields first_name and last_name, we're just asked to check if someone has mistakenly inputted a number into those fields...
in my own thinking, i think what i would do is to get the decimal value out of every character in the string and see if it is within a range of the decimal values of the letters in the alphabet.. if it is not, then i would say there's an error.
i posted this in the beginner's forum hoping someone could give me an easy answer cuz there might probably be one..
~ rockster

Dirk Schreckmann
Sheriff
Posts: 7023
A simple regular expression match might be nice to use instead.

Jim Yingst
Wanderer
Sheriff
Posts: 18671
holy crow i didnt know it'd be that complex.. thought i was dealing with a problem here with a really easy answer that i just couldn't figure out.
It's actually not that complex, now that you've provided more info. If you're trying to determine if a name is valid, couldn't you just test to see if the name contains any digits? It doesn't matter which of the formats I listed above is used - if there's any digit at all, the name is invalid. E.g. Jim7 or Go4Broke is not a name. This can be easily tested using the methods Marily and Dirk pointed out earlier.