【发布时间】:2013-11-12 03:03:53
【问题描述】:
用户输入年份并存储在 year 中。并且调用了一个方法来计算并返回将在一周中的同一天的下一年。月份和日期不会仅更改年份。在这种情况下,月份为 Jan,日期为 1。
/**
* @param theYear the year given
*/
public int yearSync(int theYear)
{
int month = 1;
int day = 1;
int year = theYear;
int aMonth = 1;
int aDay = 1;
int aYear = year++;
Date d1 = new Date(month, day, year);
Date d2 = new Date(aMonth, aDay, aYear);
boolean valid = false;
while (!valid)
{
if(d1.getDayOfWeek().equals(d2.getDayOfWeek)))//another class provided is used to
{ //calc what day of the week it is
System.out.println(aYear); //prints the year
} //that falls on the same week day as the input year
else
{
aYear++;
}
}
return aYear;
}
不要求答案只是想知道我的逻辑错误在哪里,以及在处理此类问题时我可以做些什么来改变我的思维过程。如果有任何混淆,例如,如果我输入 2014,则返回的年份为 2020;他们都在星期三跌倒。
编辑:改变循环类型。
【问题讨论】:
-
请注意,您有一个无限循环。
-
考虑使用
while循环,因为您不知道需要多少次迭代才能得到答案。 -
@SotiriosDelimanolis 我尝试了一个带有布尔值的while循环,例如
while(!valid),但我也会得到一个无限循环。我知道 for 循环是无限的,应该提到它,我的错。 -
有趣的是
i++ >= i甚至不会运行一次,而i <= i++会无限运行 -
@Claudiu 真的,我对此做了双重考虑。
标签: java for-loop while-loop logic