views:

148

answers:

3

I'm writing a program that asks the user for their birthdate and then calculates that birthdate on different planets. I am not suppose to assume how the birthdate is to be enter 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);
+2  A: 

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.

jarnbjo
Don't forget the non-integral periods of the other planets. Finding out how the locals deal with it could be problematic, though.
Hugh Brackett
Earth is also non-integral. A year is about 365.24 days
Steve Kuo
+5  A: 

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 to 1471228928 which leads to the wrong result.

The solution is append the letter L to one of your constants

long div = ( 1000 * 60 * 60 * 24 * 365L );
long age = ( today.getTime() - dateBirth.getTime() ) / div;
stacker
You beat me in time...
Willi
+2  A: 
1000 * 60 * 60 * 24 * 365

Is an int, but its to long to hold it. Make one of these a long, like:

1000L * 60 * 60 * 24 * 365
Willi