Embed presentation
Download to read offline
![Write a program to throw the InputMismatchException.
Solution
import java.util.Scanner;
import java.util.InputMismatchException;
public class TakeInput {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try {
System.out.print("Enter an integer: ");
int num = s.nextInt();
System.out.println("You entered " + num);
} catch (InputMismatchException e) {
System.out.println("You have entered invalid data");
}
}
}](https://image.slidesharecdn.com/writeaprogramtothrowtheinputmismatchexception-solutionimportjav-230129053208-53597d00/85/Write-a-program-to-throw-the-InputMismatchException-Solutionimport-jav-docx-1-320.jpg)
The document provides a Java program that demonstrates handling an InputMismatchException when taking user input. It prompts the user to enter an integer and catches the exception to display an error message if invalid data is entered. The program includes necessary imports and a try-catch block for error handling.
![Write a program to throw the InputMismatchException.
Solution
import java.util.Scanner;
import java.util.InputMismatchException;
public class TakeInput {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
try {
System.out.print("Enter an integer: ");
int num = s.nextInt();
System.out.println("You entered " + num);
} catch (InputMismatchException e) {
System.out.println("You have entered invalid data");
}
}
}](https://image.slidesharecdn.com/writeaprogramtothrowtheinputmismatchexception-solutionimportjav-230129053208-53597d00/85/Write-a-program-to-throw-the-InputMismatchException-Solutionimport-jav-docx-1-320.jpg)