DAYS IN MONTH
Thirty days hath September,
April, June and November,
All the rest have 31, etc
Write code in Java, to determine the number of days in a month
by knowing if the month is even or odd, and if it is greater than 7.
Assume that the months range from 1 to 12, and
that the second month, February, is a special case.
Show briefly how this can also be done in a second way,
but you need not do it this other way.
// Does specify days in month 1 to 12
// Except for February, month 2
int month, days;
month = 7;
if (month % 2 == 0) { // even
if (month > 7) {
days = 31;
}else{
days = 30;
}//end if
}else{ // odd month
if (month > 7) {
days = 30;
}else{
days = 31;
}//end if
}//end if
System.out.println ("Days = " + days);
mon
--1
2
3
4
5
6
7
8
9
10
11
12
days
--31
??
31
30
31
30
31
31
30
31
30
31 // Does Days in month, other ways
// Including a loop for testing
int month;
boolean even, grt7, has30;
for (month = 1; month <= 12; month++) { //test
even = (month % 2 == 0);
grt7 = (month > 7);
// Another way
if (grt7 & even) {
has30 = true;
}else{
if (! grt7 & ! even) {
has30 = true;
}else{
has30 = false;
}//endif
}// endif
Month
1
2
3
4
5
6
7
8
9
10
11
12
has30
false
true
false
true
false
true
false
false
true
false
true
false
System.out.print (month + "\t");
System.out.println (has30);
}//end for
// Yet some other ways:
has30 = true;
if (grt7 & even) {
has30 = false;
}else{
if (!grt7 & !even) {
has30 = false;
}//
}//end
//
//
Finally, the shortest way: all logic!!
has30 = (grt7 & even) | (! grt7 & ! even);
// Arrays (treated later) can also be defined as:
int daysInMonth[] = {0,31,28,31,30,31,30,31,31,30,31,30,31}
and used as:
int mayDays = daysInMonth[5];
Days in Month
of 2
Report
Tell us what’s wrong with it:
Thanks, got it!
We will moderate it soon!
Free up your schedule!
Our EduBirdie Experts Are Here for You 24/7! Just fill out a form and let us know how we can assist you.
Take 5 seconds to unlock
Enter your email below and get instant access to your document