Implementing Integer Validation Using Integer.parseInt()
The Integer.parseInt()
method attempts to convert a string into an integer. If the conversion fails, it throws a NumberFormatException
. We can use this behavior to validate integers.
- Add the following method to your
CheckInputInteger.java
file:
// Add this method inside the CheckInputInteger class
public static void checkUsingParseInt(String input) {
try {
// Attempt to parse the input string to an integer
Integer.parseInt(input);
System.out.println(input + " is a valid integer");
} catch (NumberFormatException e) {
// If parsing fails, the input is not a valid integer
System.out.println(input + " is not a valid integer");
}
}
- Update the
main
method to test this implementation:
// Modify the main method to test this implementation
public static void main(String[] args) {
// Test cases
checkUsingParseInt("123"); // Valid integer
checkUsingParseInt("12.34"); // Not an integer
checkUsingParseInt("abc"); // Not an integer
}
- The file should look like this:
import java.util.Scanner;
public class CheckInputInteger {
// Define the method inside the class
public static void checkUsingParseInt(String input) {
try {
// Attempt to parse the input string to an integer
Integer.parseInt(input);
System.out.println(input + " is a valid integer");
} catch (NumberFormatException e) {
// If parsing fails, the input is not a valid integer
System.out.println(input + " is not a valid integer");
}
}
public static void main(String[] args) {
// Test cases
checkUsingParseInt("123"); // Valid integer
checkUsingParseInt("12.34"); // Not an integer
checkUsingParseInt("abc"); // Not an integer
}
}
- Compile and run your program:
javac CheckInputInteger.java
java CheckInputInteger
You should see the following output:
123 is a valid integer
12.34 is not a valid integer
abc is not a valid integer