-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAgeException.java
More file actions
87 lines (84 loc) · 2.15 KB
/
Copy pathAgeException.java
File metadata and controls
87 lines (84 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*Write a Java program that prompts the user to enter their age. The program should:
• The input is a valid integer. The integer is within a reasonable range (e.g., between
0 and 120).
• Handle InputMismatchException: This occurs if the user enters a non-integer
value.
If the input is invalid, prompt the user to enter their age again until a valid input is
received.
Once a valid age is entered, display a message confirming the age.*/
import java.util.Scanner;
import java.lang.Exception;
class InvalidAgeException extends Exception{
public InvalidAgeException(){
super();
}
public InvalidAgeException(String msg){
super(msg);
}
}
class AgeException{
int age;
public AgeException(){
age=0;
}
public AgeException(int age) throws InvalidAgeException{
if(age<0 || age>120){
throw new InvalidAgeException("please enter age between range of 0 to 120 ");
}
this.age=age;
}
void display(){
System.out.println("age is "+this.age);
}
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
//while(age<0 || age>120)
try{
System.out.println("please enter age");
int age=sc.nextInt();
AgeException A= new AgeException(age);
A.display();
}
catch(InvalidAgeException e){
System.out.println("Exception found "+e.getMessage());
}
}
}
/*
import java.util.Scanner;
class InvalidAgeException extends Exception{
public InvalidAgeException(){
super();
}
public InvalidAgeException(String msg){
super(msg);
}
}
class AgeException{
int age;
public AgeException(){
age=0;
}
public AgeException(int age) throws InvalidAgeException{
if(age<0 || age>120){
throw new InvalidAgeException("please enter age between range of 0 to 120 ");
}
this.age=age;
}
void display(){
System.out.println("age is "+this.age);
}
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
try{
System.out.println("please enter age");
int age=sc.nextInt();
AgeException A= new AgeException(age);
A.display();
}
catch(InvalidAgeException e){
System.out.println("Exception found "+e.getMessage());
}
}
}
*/