在第二个 for 循环中设置 j = i 是否非法?它似乎适用于第一次迭代,但是,在那之后它不打印任何东西,有没有更合适的方法来做到这一点?我重写了它以使用一个while循环,它工作得很好,那么for循环有什么问题呢?
public class DaysOfChristmas {
public static void main ( String[] args )
{
int i,j;
String day = "";
String verse = "";
for ( i = 1; i <= 12; i++)
{
switch (i)
{
case 1: day = "first";
break;
case 2: day = "second";
break;
case 3: day = "third";
break;
case 4: day = "fourth";
break;
case 5: day = "fith";
break;
case 6: day = "sixth";
break;
case 7: day = "seventh";
break;
case 8: day = "eight";
break;
case 9: day = "ninth";
break;
case 10: day = "tenth";
break;
case 11: day = "eleventh";
break;
case 12: day = "twelfth";
break;
}
System.out.printf("On the %s day of Christmas my true love gave to me\n", day);
for ( j = i; j == 1; j--)
{
switch (j)
{
case 1: verse = "A Partridge in a Pair Tree";
break;
case 2: verse = "Two Turtle Doves";
break;
case 3: verse = "Three French Hens";
break;
case 4: verse = "Four Colly Birds";
break;
case 5: verse = "Five Golden Rings";
break;
case 6: verse = "Six Geese-a-Laying";
break;
case 7: verse = "Seven Swans-a-Swimming";
break;
case 8: verse = "Eight Maids-a-Milking";
break;
case 9: verse = "Nine Ladies Dancing";
break;
case 10: verse = "Ten Lords-a-Leaping";
break;
case 11: verse = "Eleven Pipers Piping";
break;
case 12: verse = "Twelve Drummers Drumming";
break;
}
System.out.printf("%s ", verse);
}
System.out.println();
}
}
}