简体   繁体   English

使用for循环在Java中测试天数

[英]Using for-loop to test day count in Java

Firstly, bear with me – I'm only about a month into Java. 首先,和我一起忍受–我只有大约一个月才学习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. 在一个练习中,要求我(用测试单位)证明从某年(x)到某年(y),从12月31日到1月1日只有一天。 They suggest that I should use a for-loop to make it run through all the years in-between our x and y year. 他们建议我应该使用for循环,使其在x和y年之间的所有年份中运行。

A predefined method called daysTill is already created. 已经创建了一个名为daysTill的预定义方法。

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.) (没有; ,由于Date声明不是语句,因此不会编译。)

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). 您还可以将i的声明移到for语句中(您之前不能这样做,因为for语句由于;提前结束,因此对于Date构造函数未定义i )。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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