-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStudent.java
More file actions
63 lines (48 loc) · 1.25 KB
/
Student.java
File metadata and controls
63 lines (48 loc) · 1.25 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
package examples;
import java.util.Scanner;
public class Student {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) throws AgeException {
if (age < 1 || String.valueOf(age).length() != 2 || String.valueOf(age).startsWith("0")) {
throw new AgeException("Invalid input. Age must be a positive integer with 2 digits. Try again.");
} else {
this.age = age;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Student [age=" + age + ", name=" + name + "]";
}
public static void main(String[] args) throws AgeException {
Student s1 = new Student();
Scanner sc = new Scanner(System.in);
System.out.print("Enter Student Name - ");
String name = sc.nextLine();
s1.setName(name);
int age;
while (true) {
System.out.print("Enter Student Age - ");
String stringAge = sc.nextLine().trim();
try {
age = Integer.parseInt(stringAge);
s1.setAge(age);
} catch (Exception e) {
System.out.println("Invalid input. Age must be a positive integer with 2 digits. Try again.");
continue;
}
break;
}
System.out.println(s1.toString());
sc.close();
}
}