0

在第二个 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();

    }
}

}

4

2 回答 2

4
for ( j = i; j >= 1; j--)

应该管用。问题是第二个循环仅在 j 为 1 时执行。否则它根本不执行。而 j 只有在 i 为 1 时才第一次为 1。

于 2012-09-30T02:49:11.820 回答
0

这样做并不违法。但是,请考虑您在循环中的条件:

 for ( j = i; j == 1; j--)

该循环只会在恰好为 1j执行。您绝对应该在这里重新考虑您的逻辑。

于 2012-09-30T02:52:00.050 回答