Java:迭代并获取每个第x项

时间:2015-10-13 19:20:37

标签: java iteration

我试图迭代一组数字,在每第6个项目之后,我需要做一个切割。以下是示例代码:

int c = 1;
StringBuffer sb = new StringBuffer();
for(int x = 1; x < 32; x++) {
    sb.append(x+ ",");
    c++;
    if (c == 6) {
        System.out.println("ADDED TO COLLECTION: " + sb.toString());
        sb = new StringBuffer();
        c = 0;
    }
}

输出:

ADDED TO COLLECTION: 1,2,3,4,5,
ADDED TO COLLECTION: 6,7,8,9,10,11,
ADDED TO COLLECTION: 12,13,14,15,16,17,
ADDED TO COLLECTION: 18,19,20,21,22,23,
ADDED TO COLLECTION: 24,25,26,27,28,29,

缺少是Nr。 31 - 如何实现?

2 个答案:

答案 0 :(得分:1)

您可以在最后添加println:

    int c = 1;
    StringBuffer sb = new StringBuffer();
    for (int x = 1; x < 32; x++) {
        sb.append(x + ",");
        c++;
        if (c == 6) {
            System.out.println("ADDED TO COLLECTION: " + sb.toString());
            sb = new StringBuffer();
            c = 0;
        }
    }
    // after the last iteration there is still something left in sb:
    System.out.println("ADDED TO COLLECTION: " + sb.toString());

您还可以添加检查sb中是否存在实际内容并跳过打印。

答案 1 :(得分:0)

只需将其添加到您的if语句|| x == 31

即可

您的代码将如下所示:

int c = 1;
StringBuffer sb = new StringBuffer();
for(int x = 1; x < 32; x++) {
    sb.append(x+ ",");
    c++;
    if (c == 6 || x == 31) {
        System.out.println("ADDED TO COLLECTION: " + sb.toString());
        sb = new StringBuffer();
        c = 0;
    }
}