用户输入一年,并存储在year
中。并且调用一种方法来计算并返回将在一周的同一天落下的下一年。月份和日期不会仅改变年份。在这种情况下,月份是1月,日期是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年;他们俩都在星期三。
编辑:更改循环类型。
答案 0 :(得分:1)
你的循环for (int i = 0; i <= i++; i++)
永远不会停止......
第一次通过时,i
设置为0,条件为i < i++
,这会将i的值更改为i + 1,但比较将成功。
因此,第一次通过循环时,i
的值为1.在循环结束时,由于i++
(为值2),它将递增它,然后它会再次与i <= i++
进行比较,但会将i设为3。
因此,值i
将在您的循环中为1,3,5,7 ...... ....
这种循环条件非常奇怪,但是,这不是真正的问题....因为它基本上与以下相同:
while (true) {...}
奇怪的是,当你实际上找到一年中具有相同yad-of-week的年份时,你不会增加年份,即aYear ++在你找到第一场比赛后永远不会改变,然后你只需要重复同样System.out.println(...)
永远。
但同样,这一点都没有意义,因为你永远不会在循环中更改日期值d2
.....
你想要的是:
while(true) {
aYear++;
Date d2 = new Date(aMonth, aDay, aYear);
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
return aYear;
}
}
答案 1 :(得分:0)
您只是递增aYear
变量,但d2
引用将始终保持创建时的aYear
初始值。因此,您还需要在for循环中更新d2
引用,以便在每个循环迭代中使用下一年。
一旦找到所需年份,您还需要打破循环。这是更新的for循环,希望它有效:
//for sake of this question I will use a for loop
for (int i = 0; i <= i++; i++)
{
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
break;
} //that falls on the same week day as the input year
else
{
aYear++;
}
d2 = new Date(aMonth, aDay, aYear);
}
return aYear;
}
答案 2 :(得分:0)
好吧,你的循环会永远持续下去。你有:
for (int i = 0; i <= i++; i++) { ... }
这相当于:
int i = 0;
while (i <= i++) {
...
}
i++
的作用是评估为i
,递增i
为1。为了使它更加明显,让我们将i++
正在做的事情解包为多个陈述:
int i = 0;
while (true) {
//left-hand-side is 'i'
int leftHandSide = i;
//right-hand-side is 'i++' which evaluates to 'i' and then 'i' is incremented
int rightHandSide = i;
i += 1;
if (leftHandSide <= rightHandSide) {
break;
}
...
}
如果你注意到这只是最终比较i <= i
,这总是正确的,所以循环永远不会破坏。
答案 3 :(得分:0)
您可以使用它来查找两个数组的匹配值。添加getDayofWeek()以及您需要的任何其他内容。
for(int x : d1){
//Some counter = 0;
for(int y : d2) {
if(x.equals(y))
//counter++;
}
System.out.println(y);
}}