aspose file tools*
The moose likes Beginning Java and the fly likes How do I check if a String is an int Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How do I check if a String is an int" Watch "How do I check if a String is an int" New topic
Author

How do I check if a String is an int

Azz Romaysa
Ranch Hand

Joined: Dec 08, 2004
Posts: 66
Hi,

I've a String a = request.getParamater("bankNr");
I wanna check if the entered value (a) is an int. Does someone know how can I do that?

Thanks,
Abu Romaysa
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

You can parse it with the static parsing methods of the Integer class, and catch an exception if its not a valid int. Or you could write a regular expresssion and check with the java.util.regex stuff.


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

Moving this to Java in General (beginner).
James Clinton
Ranch Hand

Joined: Jun 23, 2003
Posts: 190
The function you need is:


[ December 21, 2004: Message edited by: James Clinton ]
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1821

The fastest way I know of is simply to loop through the string and see if each character is in the range '0'-'9'. Having tested this before, I know that this is about a thousand times faster than trying and catching a NumberFormatException. (I haven't tested it against regex, however...)

Doing it one or two or ten at a time, it doesn't really matter what method you choose, but if you are parsing a file of thousands of these, performance does become important.

For Regex, jsut check to see if the string matches the pattern [0-9]*
[ December 21, 2004: Message edited by: Joel McNary ]

Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
sasi kala
Ranch Hand

Joined: Dec 17, 2004
Posts: 68
Hi,

This code will raise exception when bank number is not a number. in catch block you can write error message to user and any funcationality.



try
{
String a = request.getParamater("bankNr");
// 123a, a123,1a2 all are invalid numbers
int i = Integer.parseInt(a);
}

catch(NumberFormatException e)
{
System.out.println("Not a Number");
}


Hope this helps you.

All The Best.
MInu
Ranch Hand

Joined: Oct 09, 2003
Posts: 517
Hi,

This programme will check if the user input is an integer using java's regular expression.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class IntegerFinder
{
public static void main(String args[])
{
System.out.println(new IntegerFinder().isInteger(args[0]));

}

boolean isInteger(String data)
{

Pattern p = Pattern.compile("\\d*");
Matcher m = p.matcher(data);
return m.matches();

}
}


God Gave Me Nothing I Wanted<br />He Gave Me Everything I Needed<br /> - Swami Vivekananda
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Trying to check all the characters is not as easy as it sounds. You might need to test for plus and minus signs, ranges from min to max values and so on.

I'd start with the easy parse and catch (or not catch). It might be nice to pass the "int" form around after that so everybody knows it's a valid int. Try-Catch is nearly free as long as you never throw so if your data is almost always good, this is fairly low cost.

If your data may have a lot of errors AND you do thousands of them at a time, the cost of throw & catch is something to think about. But if you do one at a time as the user enters data, the speed difference is nothing to worry about.

Basic advice we repeat often:

Write first for humans to read, second for computers to process. The human time costs more money and the computer is likely to change its algorithms one day and mess up your optimizations.

Don't optimize (sacrifice human readability) until you can prove you have a problem. Get a profiler to show that a method is slow. Then, sometimes, you just gotta get tricky.

Cheers!
[ December 22, 2004: Message edited by: Stan James ]

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Using Java 1.5:
System.out.println("Is " + input + " an int? " + new Scanner(input).hasNextInt());
[ December 22, 2004: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Wow, Jim and the Scanner. Is there anything they can't do?



I guess I could try it but I'm lazy ... will that check the whole string or just the string up to the default delimiter?
[ December 22, 2004: Message edited by: Stan James ]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Wow, Jim and the Scanner. Is there anything they can't do?

It slices, it dices...

Annoyingly, I don't think Scanner works as well as it could with the enhanced for loop. (That is to say, it doesn't work with enhanced for at all.) I'm working on some utilities to help with this...

will that check the whole string or just the string up to the default delimiter?

It scans just the next token - up to the next delimiter, which is currently the default. I suppose if we want to ensure that the entire string matches an int, we should use something like

A delimiter of \\A would work as well. Or ^ or $ as long as we're not using multiline mode, which by default, we're not.
[ December 24, 2004: Message edited by: Jim Yingst ]
 
Don't get me started about those stupid light bulbs.
 
subject: How do I check if a String is an int