Java:迭代并取每第n项
Java: Iterate and take every xth item
我尝试遍历一组数字,在每第 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 - 如何实现?
只需将此添加到您的 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;
}
}
可以在最后加一个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
中是否确实有内容并跳过打印。
我尝试遍历一组数字,在每第 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 - 如何实现?
只需将此添加到您的 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;
}
}
可以在最后加一个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
中是否确实有内容并跳过打印。