Throwing.javaimport java.util.InputMismatchException; import jav.pdf
- 1. Throwing.java
import java.util.InputMismatchException;
import java.util.Scanner;
public class Throwing
{
public static void main(String[] args)
{
try{
int n = getInt();
System.out.println(n);
}
catch(IllegalArgumentException e){
System.out.println(e.getMessage());
}
}
public static int getInt()
{
// your code goes here
int n;
try{
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer: ");
n = scan.nextInt();
}
catch(InputMismatchException e){
throw new IllegalArgumentException("Invalid Input. Please enter an integer.");
}
return n;
}
}
Output:
Enter an integer:
s
Invalid Input. Please enter an integer.
Throwing.java
- 2. import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Throwing
{
public static void main(String[] args)
{
try{
int n = getInt();
System.out.println(n);
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
public static int getInt() throws IOException
{
// your code goes here
int n;
try{
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer: ");
n = scan.nextInt();
}
catch(InputMismatchException e){
throw new IOException("Invalid Input. Please enter an integer.");
}
return n;
}
}
Output:
Enter an integer:
d
Invalid Input. Please enter an integer.
Solution
- 3. Throwing.java
import java.util.InputMismatchException;
import java.util.Scanner;
public class Throwing
{
public static void main(String[] args)
{
try{
int n = getInt();
System.out.println(n);
}
catch(IllegalArgumentException e){
System.out.println(e.getMessage());
}
}
public static int getInt()
{
// your code goes here
int n;
try{
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer: ");
n = scan.nextInt();
}
catch(InputMismatchException e){
throw new IllegalArgumentException("Invalid Input. Please enter an integer.");
}
return n;
}
}
Output:
Enter an integer:
s
Invalid Input. Please enter an integer.
Throwing.java
- 4. import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Throwing
{
public static void main(String[] args)
{
try{
int n = getInt();
System.out.println(n);
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
public static int getInt() throws IOException
{
// your code goes here
int n;
try{
Scanner scan = new Scanner(System.in);
System.out.println("Enter an integer: ");
n = scan.nextInt();
}
catch(InputMismatchException e){
throw new IOException("Invalid Input. Please enter an integer.");
}
return n;
}
}
Output:
Enter an integer:
d
Invalid Input. Please enter an integer.