When reading numeric input using the Scanner
class, it's important to handle potential exceptions that may occur. One common exception is the InputMismatchException
, which is thrown when the user enters a non-numeric value.
To handle these exceptions, you can use a try-catch
block to catch the exception and provide appropriate error handling. Here's an example:
import java.util.InputMismatchException;
import java.util.Scanner;
public class NumericInputException {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter a long integer: ");
long longNumber = scanner.nextLong();
System.out.println("You entered: " + longNumber);
} catch (InputMismatchException e) {
System.out.println("Error: Invalid input. Please enter a valid long integer.");
} finally {
scanner.close();
}
}
}
In this example, we wrap the scanner.nextLong()
call in a try
block. If the user enters a non-numeric value, the InputMismatchException
is caught, and we print an error message. Finally, we close the Scanner
object in the finally
block to ensure that system resources are properly released.
By handling exceptions, you can make your Java applications more robust and provide a better user experience by gracefully handling unexpected input.
Additionally, you can use a loop to repeatedly prompt the user for input until a valid long integer is entered. Here's an example:
import java.util.InputMismatchException;
import java.util.Scanner;
public class NumericInputException {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long longNumber;
boolean validInput = false;
while (!validInput) {
try {
System.out.print("Enter a long integer: ");
longNumber = scanner.nextLong();
validInput = true;
System.out.println("You entered: " + longNumber);
} catch (InputMismatchException e) {
System.out.println("Error: Invalid input. Please enter a valid long integer.");
scanner.nextLine(); // Clear the input buffer
}
}
scanner.close();
}
}
In this example, we use a while
loop to repeatedly prompt the user for input until a valid long integer is entered. The scanner.nextLine()
call is used to clear the input buffer after an InputMismatchException
is caught, allowing the user to enter a new value.
By handling exceptions and providing a robust input validation process, you can ensure that your Java applications can gracefully handle a variety of user inputs and provide a better overall user experience.