How To Determine If A String Represents An Integer ?

M

MrBill

Hi Experts,
I have a String of two to four characters in length. I would like to
determine if it is an integer (each character is in the set 0:9). I could
check each character individually but there must be an easier (and faster
way). Any suggestions?
Thanks,
Bill
 
M

Marco Schmidt

MrBill:
I have a String of two to four characters in length. I would like to
determine if it is an integer (each character is in the set 0:9). I could
check each character individually but there must be an easier (and faster
way). Any suggestions?

public static boolean isValidNumber(String s) {
try {
int i = Integer.parseInt(s);
return s.length() > 1 && s.length() < 5;
}
catch (NumberFormatException nfe) {
return false;
}
}

Not necessarily faster than anything "handmade", but probably more
readable.

Regards,
Marco
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top