3 回答

TA貢獻(xiàn)1818條經(jīng)驗(yàn) 獲得超8個(gè)贊
使用模運(yùn)算符和單個(gè)循環(huán)的解決方案。沒(méi)有 IndexOutOfBounds 的風(fēng)險(xiǎn)。
for (int i = 0; i < list.length; i++) {
if (i % 6 > 2) {
System.out.println(list[i]);
}
}
i % 6 < 3如果您想要數(shù)組中每 6 個(gè)元素中的前 3 個(gè),則可以將條件翻轉(zhuǎn)為。
編輯:以下內(nèi)容接受您的輸入并將其放入List<String[]>每個(gè)元素包含 3 行的位置。
import java.nio.file.*;
import java.util.stream.Stream;
import java.util.*;
import java.nio.charset.Charset;
public class Partition2 {
public static void main(String[] args) {
String[] input = ...
try (Stream<String> stream = Arrays.stream(input)) {
// https://stackoverflow.com/a/34759493/3717691
String[] array = stream.map(line -> line.trim()).filter(line -> !line.isEmpty()).toArray(String[]::new);
List<String[]> results = new ArrayList<String[]>();
String[] tmp = new String[3];
for (int i = 0; i < array.length; i++) {
tmp[i % 3] = array[i];
if (i % 3 == 2) {
results.add(tmp);
tmp = new String[3];
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
for(int i=3;i<s1.length;i+=6){
for(int j=0;j<3;j++){
s1[i+j]; // here is your element
}
}
IndexOutOfBoundsException如果 arrag 大小不能被 6 整除,只需調(diào)整循環(huán)條件即可

TA貢獻(xiàn)1943條經(jīng)驗(yàn) 獲得超7個(gè)贊
您可以使用 Java 8 流。如果s有類型E:
List<E> collect =
IntStream.range(0, s.length) // 0...n-1
.filter(i -> i/3%2 == 0) // g = i/3 is the number of the group and we take one group out of to (g % 2 == 0)
.mapToObj(i -> s[i]) // take s[i]
.collect(Collectors.toList());
添加回答
舉報(bào)