寻找不同星球上的年龄

Kat*_*Kat 0 java string user-input

我正在编写一个程序,询问用户他们的出生日期,然后计算他们在不同行星的年龄.我不假设如何输入生日,除了每个数字之间有一个空格.

我现在的代码现在不符合这些规范,我不知道如何编写它.我也有计算今天我的年龄的问题.当我输入我的出生日期并打印出年龄时,它现在告诉我,当我打印出dateBirth时,我已经是407了,今天这两个日期都是正确的.

System.out.print("Please enter your birthdate (mm dd yyyy): ");
birthdate = scan.nextLine();

DateFormat df = new SimpleDateFormat("MM dd yyyy");
Date dateBirth = df.parse(birthdate);
Calendar calBirth = new GregorianCalendar();
calBirth.setTime(dateBirth);

Calendar calDay = new GregorianCalendar();
today = calDay.getTime();
age = (today.getTime() - dateBirth.getTime()) / (1000 * 60 * 60 * 24 * 365);
Run Code Online (Sandbox Code Playgroud)

sta*_*ker 6

1000*60*60*24*365实际上31536000000大于Integer.MAX_VALUE会导致溢出.作为一个整数,它将被评估1471228928导致错误的结果.

解决方案是将字母L附加到您的常量之一

long div = ( 1000 * 60 * 60 * 24 * 365L );
long age = ( today.getTime() - dateBirth.getTime() ) / div;
Run Code Online (Sandbox Code Playgroud)