I hope to write a small method to do the following things: For example, the string a = "a123", then the method should return fulse; the string b = "111", it should return true. It means only the string is an int, it should return true, all the other cases should return false. Does anyone can help me? Thank you!
Asked
Active
Viewed 4,512 times
4
-
1negative case? "-1345" ? – Kent Nov 18 '12 at 21:14
-
Seems like a homework question to me... add a homework tag if so – recursion.ninja Nov 18 '12 at 21:16
-
1@awashburn Homework tag is deprecated. – arshajii Nov 18 '12 at 21:17
-
@A.R.S. I did not know that the homework tag was depreciated ;) – recursion.ninja Nov 18 '12 at 21:32
2 Answers
8
You can use Integer.parseInt(integerString);
public boolean isInteger(String integerString){
try{
Integer.parseInt(integerString);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
a NumberFormatException means parsing will not be successful hence the String is not an integer.

Nitin Chhajer
- 2,299
- 1
- 24
- 35
4
If you meant you wanted a string that's composed only of the digits 0-9 (and with arbitrary length) you can just use the regular expression "\\d+"
, i.e. str.matches("\\d+")
.
If you want to take into account positive and negative signs you could use "[+-]?\\d+"
.
If you're considered with length (the primitive int
typo can't have more than 10 digits) you could use "[+-]?\\d{1,10}+"
.

arshajii
- 127,459
- 24
- 238
- 287
-
1That good for number validation, but integer has also some length. – Damian Leszczyński - Vash Nov 18 '12 at 21:14
-
No. What I meant is integer is shorten than long. `+` is only responsible for that empty string is not treated as valid. – Damian Leszczyński - Vash Nov 18 '12 at 21:22