How to determine whether a string contains an integer?
Say you have a string that you want to test to make sure that it contains an integer before you proceed 开发者_开发问答with other the rest of the code. What would you use, in java, to find out whether or not it is an integer?
If you want to make sure that it is only an integer and convert it to one, I would use parseInt in a try/catch
. However, if you want to check if the string contains a number then you would be better to use the String.matches with Regular Expressions: stringVariable.matches("\\d")
You can check whether the following is true: "yourStringHere".matches("\\d+")
String s = "abc123";
for(char c : s.toCharArray()) {
if(Character.isDigit(c)) {
return true;
}
}
return false;
I use the method matches() from the String class:
Scanner input = new Scanner(System.in)
String lectura;
int number;
lectura = input.next();
if(lectura.matches("[0-3]")){
number = lectura;
}
This way you can also validate that the range of the numbers is correct.
You can use apache StringUtils.isNumeric .
User regular expression:
Pattern.compile("^\\s*\\d+\\s*$").matcher(myString).find();
Just wrap Integer.parse() by try/catch(NumberFormatException)
You might also want to have a look at java.util.Scanner
Example:
new Scanner("456").nextInt
You could always use Googles Guava
String text = "13567";
CharMatcher charMatcher = CharMatcher.DIGIT;
int output = charMatcher.countIn(text);
That should work:
public static boolean isInteger(String p_str)
{
if (p_str == null)
return false;
else
return p_str.matches("^\\d*$");
}
If you just want to test, if a String contains an integer value only, write a method like this:
public boolean isInteger(String s) {
boolean result = false;
try {
Integer.parseInt("-1234");
result = true;
} catch (NumberFormatException nfe) {
// no need to handle the exception
}
return result;
}
parseInt
will return the int
value (-1234 in this example) or throw an exception.
int number = 0;
try {
number = Integer.parseInt(string);
}
catch(NumberFormatException e) {}
Use the method Integer.parseInt() at http://docs.oracle.com/javase/10/docs/api/java/lang/Integer.html
精彩评论