In: Computer Science
For practice using exceptions, this exercise will use a try/catch block to validate integer input from a user. Write a brief program to test the user input. Use a try/catch block, request user entry of an integer, use Scanner to read the input, throw an InputMismatchException if the input is not valid, and display "This is an invalid entry, please enter an integer" when an exception is thrown. InputMismatchException is one of the existing Java exceptions thrown by the Scanner if the input does not match the type requested.
Please upvote if you like the answer, as it helps the community a lot.
Also if you have any doubts, feel free to ask in comments, we will reach you ASAP.
Code(Solution.Java):
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be same as file name. */
class Solution
{
public static void main (String[] args) throws
java.lang.Exception
{
// your code goes here
Scanner sc = new
Scanner(System.in);
//Try Catch Block
try{
int x =
sc.nextInt();
System.out.println("You entered "+x);
} catch(InputMismatchException e)
{
System.out.println("This is an invalid entry, please enter an
integer");
}
}
}
SAMPLE I/Os:
Input:
42
Output:
You entered 42
Input:
Alex
Output:
This is an invalid entry, please enter an integer