//import Scanner class
import java.util.Scanner;
// create class for age
validation
class Form
{
//define a variable
private final int value;
//
constructor of class
public Form(int v)
{
// check condition of age
if (v < 0 || v > 100)
{
// if age exceeds range then generate exception
throw new IllegalArgumentException(Integer.toString(v));
}
this.value = v;
}
// define
function to get value of age
public int getValue()
{
return value;
}
}
class IllegalArgumentEx
{
// define main method
public static void main(String[] args)
{
// use scanner object to take input of age by user
Scanner sc = new Scanner(System.in);
System.out.println("Enter age: ");
int age=sc.nextInt();
// validate
input age by constructor
Form obj = new Form(age);
System.out.println(obj.getValue());
}
}
Another way
//import Scanner class
import java.util.Scanner;
// create class for age
validation
class Form
{
//define a variable
private final int value;
//
constructor of class
public Form(int v)
{
// check condition of age
if (v < 0 || v > 100)
{
// if age exceeds range then generate exception
throw new IllegalArgumentException();
}
this.value = v;
}
// define
function to get value of age
public int getValue()
{
return value;
}
}
class IllegalArgumentEx
{
// define main method
public static void main(String[] args)
{
// use scanner object to take input of age by user
Scanner sc = new Scanner(System.in);
System.out.println("Enter age: ");
int age=sc.nextInt();
// validate
input age by constructor
Form obj = new Form(age);
System.out.println(obj.getValue());
}
}