简体   繁体   中英

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?

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));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM