Straightforward mathematical calculations are performed with mathematical operations, like addition and mulitiplication. Other "calculations" require decisions and must use if.. commands to produce correct results. An example is the number of days in a month.
Starting with the number of the month, as well as the year, we check whether the month number is 2 (February), and then whether the year is divisible by 4 to decide whether it has 28 days or 29. The other months are a bit simpler, always having either 30 or 31 days.
Write a method that accepts 2 parameters - the month number and the year number - and returns the number of days in that month.
public int daysInMonth(int month, int
year)
{
if (month ==
2) //
February
{
if (year % 4 == 0) // leap
year
{ return 29;
}
else
{ return 28; }
}
else if (month == 4 || month
== 6 || month == 9 || month == 11)
{
return 30; }
else
{ return 31; }
return -1;
// in case the month number is not valid
}
//** The REAL calculation for leap years is actually more complex, as
century years
//** (divisible by 100) are not leap years, but years
divisible by 400 ARE leap years.
//** The simplification above works
from year 2000 until 2099.