Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 203
  • Last Modified:

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??
0
mte01
Asked:
mte01
  • 4
  • 2
  • 2
  • +1
2 Solutions
 
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
 
RoyalNepalCommented:
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
CEHJCommented:
An exception-free method would be

if (s.matches("\\d+"))
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

Featured Post

Become an Android App Developer

Ready to kick start your career in 2018? Learn how to build an Android app in January’s Course of the Month and open the door to new opportunities.

  • 4
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now