Aphex
Aphex

Reputation: 408

Using for-loop to test day count in Java

Firstly, bear with me – I'm only about a month into Java.

In an exercise, I'm asked to proof (with a test unit) that from a certain year (x) to a certain other year (y) that there are only one day between 31st of December and the 1st of January. They suggest that I should use a for-loop to make it run through all the years in-between our x and y year.

A predefined method called daysTill is already created.

So far, I've come up with this ugly piece of code, which doesn't work:

public void testYearEnd()
{int i;
       for(i = 1635; i <=2300; i++);
            Date date1 = new Date(i, 31, 12);
            Date date2 = new Date(i, 01, 01);
            assertEquals(1, date1.daysTill(date2));
}

Can anyone bear to point out exactly where my code is failing on me?

Upvotes: 1

Views: 408

Answers (1)

Jeffrey Bosboom
Jeffrey Bosboom

Reputation: 13663

Two problems here: you have a stray ; that's ending your for-statement without a body, making it a no-op, and missing braces around the intended body. (Without the ;, this wouldn't compile as the Date declaration isn't a statement.)

You can also move the declaration of i into the for-statement (you couldn't before because the for-statement ended early due to the ;, so i was undefined for the Date constructors).

The code should be

public void testYearEnd() {
    for (int i = 1635; i <= 2300; i++) {
        Date date1 = new Date(i, 31, 12);
        Date date2 = new Date(i, 01, 01);
        assertEquals(1, date1.daysTill(date2));
    }
}

Upvotes: 2

Related Questions