我是編程和Java的新手,我試圖通過Project Euler網站來教自己。我試圖完成這個問題:http://projecteuler.net/problem=19,那就是:爪哇,從1901年到2000年這個月的第一個月的星期日計數
多少週日二十世紀 (1901年1月1日至31月2000)期間,在第一個月的下跌?
我想解決這個問題的方法是製作一個二維數組,代表一個calander,並通過計數到7來循環訪問數組,然後每次計數到7時,將1加到該點在數組中。最後,我會對數組的第一行進行求和,這應該是本月的第一天有多少個星期日。
但是我的循環有問題,我的計數到7個月才重置,我不知道如何阻止它做到這一點?
這裏是我的代碼:
public class Problem019 {
public static void main (String[] args){
//System.out.println(LeapYearTest(1996));
int ThirtyOne = 31;
int Thirty = 30;
int FebNorm = 28;
int FebLeap = 29;
int a, b, c, Day, e = 0, f = 0;
int Calander[] []= new int [12] [] ;
Calander[0] = new int [ThirtyOne];
Calander[1] = new int [FebNorm];
Calander[2] = new int [ThirtyOne];
Calander[3] = new int [Thirty];
Calander[4] = new int [ThirtyOne];
Calander[5] = new int [Thirty];
Calander[6] = new int [ThirtyOne];
Calander[7] = new int [ThirtyOne];
Calander[8] = new int [Thirty];
Calander[9] = new int [ThirtyOne];
Calander[10] = new int [Thirty];
Calander[11] = new int [ThirtyOne];
for (a=1901;a<2001;a++){
//System.out.println(a);
if (LeapYearTest(a))
{
Calander[1] = new int [FebLeap];
}
else
{
Calander[1] = new int [FebNorm];
}
for (e=0;e<Calander.length;e++)
{
System.out.println("e: " + e);
f=0;
while (f<Calander[e].length)
{
//System.out.println(Calander[e].length);
Day=1;
while (Day<8 && f<Calander[e].length)
{
System.out.println("f: " + f + "\tDay: " + Day + "\tCalander[e][f]: " + Calander[e][f]);
Day++;
f++;
if (f<Calander[e].length && f!=0 && Day==7)
{
Calander[e][f]+= 1;
}
}
}
}
//System.out.println(a);
}
for (b=0;b<Calander.length;b++)
{
System.out.print(Calander[0][b]);
}
}
public static boolean LeapYearTest(int x)
{
if (x%4==0 || x%400==0){
return true;
}
if (x%100==0){
return false;
}
else return false;
}
}
這是它打印,e是一個月,f是在一個月的日子裏,和天計數至7:
f: 25 Day: 5 Calander[e][f]: 0
f: 26 Day: 6 Calander[e][f]: 0
f: 27 Day: 7 Calander[e][f]: 100
f: 28 Day: 1 Calander[e][f]: 0
f: 29 Day: 2 Calander[e][f]: 0
**f: 30 Day: 3 Calander[e][f]: 0**
e: 10
**f: 0 Day: 1 Calander[e][f]: 0**
f: 1 Day: 2 Calander[e][f]: 0
f: 2 Day: 3 Calander[e][f]: 0
如何我可以設置循環,以便Day在本月末不重置?還是有另一種方法來解決這個問題,不涉及這麼多的嵌套循環?
謝謝!
所有這些陣列是矯枉過正。你只需要迭代和增加Sun 1st的總數。你用一個計數器0-6和另一個計數器並行迭代,計算當前月份的天數。 – 2012-04-29 07:50:20
另外,除了每天循環之外,還有更多聰明的方法來計算本月第一個月的星期日。另外 - 如果沒有其他人會看到您的代碼,但您拼錯* Calendar *,並且Java編碼約定建議使用camelCase變量名稱(第一個字母爲小寫),那麼這不重要。 – rob 2012-04-29 08:14:11
@Marko:對不起,我不明白,你能詳細說一下嗎? – Keith 2012-04-29 08:22:13