-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculadoraEdad.java
More file actions
58 lines (50 loc) · 2.93 KB
/
CalculadoraEdad.java
File metadata and controls
58 lines (50 loc) · 2.93 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
import javax.swing.JOptionPane;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class CalculadoraEdad {
public static void main(String[] args) {
// Pedir la fecha con el formato que Java necesita
String input = JOptionPane.showInputDialog(null, "Enter your date of birth\nFormat: DD/MM/YYYY", "Date Input", JOptionPane.QUESTION_MESSAGE);
// Filtro básico de seguridad
if (input != null && !input.isEmpty()) {
try {
/*
* Se usa letras minúsculas 'uuuu' en lugar de 'yyyy' cuando se usa el modo
* estricto (es una regla técnica de Java para fechas históricas).
*/
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/uuuu")
.withResolverStyle(java.time.format.ResolverStyle.STRICT);
// Convertir el texto a una fecha real
LocalDate birthDate = LocalDate.parse(input, formatter);
LocalDate currentDate = LocalDate.now();
// Calcular la diferencia exacta
Period period = Period.between(birthDate, currentDate);
int years = period.getYears();
// Lógica y validación
if (birthDate.isAfter(currentDate)) {
// Si la fecha es del futuro
JOptionPane.showMessageDialog(null, "Error! This date has not occurred yet.", "Time Traveler Detected", JOptionPane.ERROR_MESSAGE);
} else if (years > 122) {
// El caso de Jeanne Calment y el récord Guinness
String recordMessage = "CAUTION! You entered " + years + " years.\n\n"
+ "This exceeds the world record of Jeanne Calment (122 years).\n"
+ "Please verify if the birth year is correct.";
JOptionPane.showMessageDialog(null, recordMessage, "Possible Record or Error", JOptionPane.WARNING_MESSAGE);
} else {
// Caso normal y exitoso
String result = "Confirmed Age:\n" + years + " years, " + period.getMonths() + " months, and "
+ period.getDays() + " days.";
JOptionPane.showMessageDialog(null, result, "Exact Result", JOptionPane.INFORMATION_MESSAGE);
}
} catch (DateTimeParseException e) {
// Si el usuario escribe texto o pone una fecha imposible como 31/02/1990
JOptionPane.showMessageDialog(null, "Invalid date format or non-existent date. Remember: DD/MM/YYYY",
"Format Error", JOptionPane.ERROR_MESSAGE);
}
} else {
JOptionPane.showMessageDialog(null, "Operation cancelled.");
}
}
}