A few days ago, a user asked how to calculate the age in the Linux Bash shell
Once the question was answered, he told me if they could not calculate, in addition to the age in years, the months and days.
I have done the exercise in Java, and due to the short time available, I have not yet been able to adapt it to the command interpreter, I am working on it
The question came with its code and asked how to complete it, I have translated it into Java and it has seemed interesting enough to publish it in this language
It could be done with methods and in many fewer lines, but the fun is in doing it without shortcuts
public static void main(String[] args){
Scanner teclado = new Scanner(System.in);
System.out.println("Ingrese su año de nacimiento");
int a = teclado.nextInt();
System.out.println("Ingrese su mes de nacimiento");
int m = teclado.nextInt();
System.out.println("Ingrese su dia de nacimiento");
int d = teclado.nextInt();
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int anio = localDate.getYear();
int mes = localDate.getMonthValue();
int dia = localDate.getDayOfMonth();
int day = dia - d;
int year = anio - a;
int month = mes - m;
int MES = month + 12;
if (m > mes){
System.out.println("Tiene " + year + " años");
System.out.println("Con " + MES + " meses");
System.out.println("Con " + day + " dias");
}else{
System.out.println("Tiene " + year + " años");
System.out.println("Con " + month + " meses");
System.out.println("Con " + day + " dias");
}
}
The code result for the exercise is as follows
Methods have been separated so as not to overload the main method, I know there are several ways to solve the problem, but this is the one that has occurred to me.