-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshortIntroduction.java
More file actions
79 lines (60 loc) · 2.08 KB
/
shortIntroduction.java
File metadata and controls
79 lines (60 loc) · 2.08 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
import java.time.Year;
import java.util.Scanner;
class shortIntroduction {
private static final Scanner scanner = new Scanner(System.in);
private static int yearOfBirth;
public static void main(String[] args) {
String UserName = getName();
Integer age = getBirth();
scanner.close();
writeToConsole("\n\n\n");
writeToConsole("Hello " + UserName + ", your age is: " + age);
writeToConsole("Your life runs from " + yearOfBirth + " to " + currentYear() + " (today).");
}
/* NOTE get the name of the person */
private static String getName() {
writeToConsole("Enter your name: ");
String name = scanner.nextLine().trim();
if (name.isEmpty()) {
writeToConsole("Name cannot be empty");
return getName();
}
return name.trim();
}
/* NOTE asks for the year of birth */
private static int getBirth() {
writeToConsole("Enter your year of birth: ");
String yearOfBirthstr = scanner.nextLine().trim();
try {
int year = Integer.parseInt(yearOfBirthstr);
if (yearOfBirthstr.isEmpty()) {
writeToConsole("Year of birth cannot be empty");
return getBirth();
}
if (yearOfBirthstr.length() != 4) {
writeToConsole("Year of birth must be 4 digits");
return getBirth();
}
yearOfBirth = year;
int age = getAge(year);
return age;
} catch (Exception e) {
writeToConsole("Year of birth must be a number");
return getBirth();
}
}
/* NOTE calculate the current age */
private static int getAge(int YearOfBirth) {
int year = currentYear();
int age = year - YearOfBirth;
return age;
}
/* NOTE get current year */
private static int currentYear() {
return Year.now().getValue();
}
/* NOTE write to console */
private static void writeToConsole(String message) {
System.out.println(message);
}
}