查找不同行星上的年龄
我正在编写一个程序,询问用户的出生日期,然后计算他们在不同行星上的年龄。除了每个数字之间有一个空格之外,我不打算假设如何输入生日。
我现在拥有的代码不符合这些规范,我不知道如何编写它。我在计算我今天的年龄时也遇到问题。当我输入我的生日并打印出年龄时,它当前告诉我我是 407,但是当我打印出 dateBirth 和今天时,这两个日期都是正确的。
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);
I'm writing a program that asks the user for their birthdate and then calculates their age in years of different planets. I am not suppose to assume how the birthdate is to be entered except that there is one white space between each number.
The code I have right now does not meet these specifications right now and I'm not sure how to write it otherwise. I am also having problem calculating what my age would be today. When I enter my birthdate and print out age, it currently tells me that I'm 407 yet when I print out dateBirth and today, both of those dates are correct.
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
1000 * 60 * 60 * 24 * 365 实际上是
31536000000
,它比 Integer.MAX_VALUE 大,这会导致溢出。作为整数,它将被计算为1471228928
,这会导致错误的结果。解决方案是将字母 L 附加到您的常量之一
1000 * 60 * 60 * 24 * 365 is actually
31536000000
which is bigger than Integer.MAX_VALUE this causes an overflow. As an integer it would be evaluated to1471228928
which leads to the wrong result.The solution is append the letter L to one of your constants
您应该检查表达式
1000 * 60 * 60 * 24 * 365
的计算结果是否为您期望的结果,如果不是,请找到一种方法来获得期望的结果。也许你甚至应该考虑一下,在地球上,我们有所谓的闰年,你可以将你的问题标记为家庭作业。You should check if the expression
1000 * 60 * 60 * 24 * 365
evaluates to the result you are expecting and if not, find a way to get the expected result. Perhaps you should even consider that on earth, we have so called leap years and that you could tag your question as homework.是一个int,但是保存它太长了。将其中之一设为很长,例如:
Is an int, but its to long to hold it. Make one of these a long, like: