Java:如何摆脱列表中的一些数字?

时间:2014-06-02 02:48:18

标签: java

我真的不知道怎么解释这个,但我可以证明。我想要实现的目标是第一个循环产生数字1,2,3,4,5。然后第二个循环产生数字1,2,3,4,5,6,7,8,9。我希望第二个循环输出数字6,7,8,9。然后在第三个循环中输出10,11,12,13,14,15。现在我该怎么做呢?

                int horse= 5

        for (int w =1; w <= horse; w++)
        {
            System.out.println(w + " The first loop");
        }

        int test= horse + 4;

        for (int w =1; w <= test; w++)
        {
            System.out.println(w + " The second loop");

        }

        int try = test + 6;

        for (int w =1; w <= try; w++)
        {
            System.out.println(w + " The third loop");
        }

2 个答案:

答案 0 :(得分:1)

每次都不要将w变量重新初始化为1。你可以简单地省略它。

    int horse= 5;
    int w;
    //loop from 1 to 5
    for (w =1; w <= horse; w++)
    {
        System.out.println(w + " The first loop");
    }

    int test= horse + 4;
    //loop from 6 to 9
    //here the initial value of w is 6 from the previous loop
    for (; w <= test; w++)
    {
        System.out.println(w + " The second loop");

    }

    int try0 = test + 6;
    //loop from 10 to 15
    //here the initial value of w is 10 from the previous loop
    for (; w <= try0; w++)
    {
        System.out.println(w + " The third loop");
    }

请注意try是保留的系统关键字,因此请将其重命名为try0

答案 1 :(得分:0)

这将满足您的需求(see live example here):

// put the increments in an array instead of a scalar.
int[] loops = {5, 4, 6};
String[] names = {"first", "second", "third"};

for(int i = 0, sum = 0; i < loops.length; sum += loops[i++])
    for(int j = sum; j < sum + loops[i]; j++)
        System.out.println((j + 1) + " The " + names[i] + " loop");

<强>输出:

1 The first loop
2 The first loop
3 The first loop
4 The first loop
5 The first loop
6 The second loop
7 The second loop
8 The second loop
9 The second loop
10 The third loop
11 The third loop
12 The third loop
13 The third loop
14 The third loop
15 The third loop