
Suzanne O. answered 10/03/19
International Experience and Multiple State Certifications
I think you are doing pretty well for a beginner. As for more efficient ways to do things, or more elegant, sure there are. That's the beauty of programming, there is always more than one way to get the desired result. Mostly it would be streamlining the code in this specific example, or snazzing things up with a loop to repeat the leap year check or exit.
From the original problem:
(i) A Year is a Leap Year if the year can be divided by 4 but not by 100
(eg: 1976).
(ii) A year that can be divided by both 4 and 100 is Leap Year if it can also
be divided by 400.
I am wondering what years you tested with, since your nested ifs should be giving only years like 2000 the "Leap Year" thumbs up, and giving a false negative to years like 1960?
I am thinking that using a logical operator in your if statement would work better, and be more efficient.
The pseudo code would look like:
if p can be divided by 4 and not by 100 or p can be divided by 4 and by 100 and by 400
print "Leap Year"
else
print "Not a Leap Year"
the actual code snippet would look like :
if (p%4 ==0 && p%100!=0) || (p%4==0 && p%100==0 && p%400==0)
{
System.out.println("Leap Year");
}
else
{
System.out.println("Not a Leap Year");
}
Since the year either is or isn't a leap year, the second check that you wrote in (after your nested ifs) is not needed.
Good test years would be 1951, 1960, 2000 and 3000, since the first and last are not leap years and the middle two are.
What do you think?
Take a look at (https://www.programiz.com/java-programming/operators) for more on operators.
Ashley P.
Thanks a lot for your response. The explanation was very clear and I was able to correct the errors in my code10/07/19