Some Integer check method

Hey experts,

 Is there any java built-in method similar to VB's IsNumeric method; I need a methd that checks if a string variable is an integer or no. I know I can do it by trying to instantiate a new object of class Integer, and an exception would occur if it's not an integer, but I am trying to see if there is a better way.....any help??
LVL 3
mte01Asked:
Who is Participating?
 
CEHJConnect With a Mentor Commented:
An exception-free method would be

if (s.matches("\\d+"))
0
 
CEHJCommented:
Long.parseLong(x)

will throw an Exception if not a number
0
 
mte01Author Commented:
>>CEHJ

I am trying to see something better than having to check for an exception....the Integer.getInteger method seems good enough....
0
Cloud Class® Course: Microsoft Windows 7 Basic

This introductory course to Windows 7 environment will teach you about working with the Windows operating system. You will learn about basic functions including start menu; the desktop; managing files, folders, and libraries.

 
RoyalNepalConnect With a Mentor Commented:
No...there is no such built in function in java...

Two ways:

1)Throws an exception if its not a number..
2) write a function...

//Here is the code for that.....

private static final boolean isNumeric(final String s) {
  final char[] numbers = s.toCharArray();
  for (int x = 0; x < numbers.length; x++) {      
    final char c = numbers[x];
    if ((c >= '0') && (c <= '9')) continue;
    return false; // invalid
  }
  return true; // valid
}

Cheers.

0
 
mte01Author Commented:
>>CEHJ

Great..that'll do the trick...thanks for your help!
0
 
CEHJCommented:
:-)
0
 
ksivananthCommented:
i think it should be ^\\d+, simply \\d going to return true if there is a number
0
 
CEHJCommented:
>>simply \\d going to return true if there is a number

No. Returns true if *only* a number
0
 
ksivananthCommented:
agree

confused with find method
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.