I decided to start to learn to program, and I've already gone through a few tutorials. But, at this point the knowledge hasn't sunk in. I was hoping to get some help in base knowledge. I would appreciate an explanation of what is wrong... not a code fix.
I've given myself the task of writing a program with the following goals:
1. How many days have you been alive?
2. How many hours have you been alive?
3. How many minutes have you been alive?
4. How many seconds have you been alive?
5. What milestones have you passed?
a. 16 - Driver's License
b. 18 - Adult
c. 21 - Alcohol
d. 25 - Cheaper insurance
e. 35 - Can be president.
f. 55 - Senior citizen
g. 65 - Retirement
h. 100 - Centennial
I stole (borrowed?) some code from a website (I would give proper credit to the author, but I lost the website) and have been trying to manipulate it to gain some understanding of how things work in Java.
The error is you cannot have assignment statements outside a block (say method block). If you need to assign values to your variables in your class body, you have to specify them during declaration itself.
If you really want to assign values to the 3 variables outside then you can do something like this:
Sorry John I realized later that me and you are on the same lines!!!
Joined: Aug 06, 2012
Thank you both for your fast reply. I can see that this is going to be a helpful forum.
So, I guess it is technically accurate to assign values to the variables at the declaration. Would that be best practice? Where/when should I be assigning these values?
Initial values can be assigned when variables are declared, in constructors, or prior to their first use. It depends on your application logic. Instance variables like your month, day, and year variables are assigned default values. For object references, the default is null. For int, the default is 0. Therefore, explicitly assigning 0 to the instance variables as suggested in previous replies is actually redundant.