For Loop有两个变量

时间:2012-09-30 02:47:00

标签: java

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

    }
}

}

2 个答案:

答案 0 :(得分:4)

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

应该有效。问题是第二个循环仅在j为1时执行。否则它根本不执行。当i为1时,j仅为第一次。

答案 1 :(得分:0)

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

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

j正好为1 时,该循环才会执行。你一定要在这里重新思考你的逻辑。