The Integer class has a number of static methods for parsing strings. For the case where we want to check if if a string contains a valid integer we can use the method Integer.parseInt() and catch the exception that is thrown when the number cannot be parsed.
package com.learnjava.string; public class IntegerCheck { public static void main(String[] args) { String[] input = { "abc", "9", "352", "5g", "-86", "6.7" }; // Loop through an array of Strings, // testing if each is a integer or not for (int i=0; i<input.length; i++) { // Test if next string is a integer boolean isInteger = isInteger(input[i]); if (isInteger) { System.out.println(input[i]+" is an integer"); } else { System.out.println(input[i]+" is not an integer"); } } } public static boolean isInteger(String s) { boolean isValidInteger = false; try { Integer.parseInt(s); // s is a valid integer isValidInteger = true; } catch (NumberFormatException ex) { // s is not an integer } return isValidInteger; } }
…was looking for a solution as we also use the try catch method but it’s not really satisfying, a try/catch in this case is not really an elegant solution.
For the second method we use a slightly simplified one:
public static boolean isInteger(String s) {
try
{
Integer.parseInt(s);
// s is a valid integer
return true;
}
catch (NumberFormatException ex)
{
return false;
}
}
I’d like to add that both function will be spotted by sonar as a Critical error as the value returned by parseInt is ignored.
Another option would be to use regex to check the string, or loop through the characters.