3 回答
TA贡献1859条经验 获得超6个赞
这是一个示例,可让您为每个列表提供大小列表,因此您可以轻松生成您指定的输出,而不必在每个列表中包含 3 个名称:
package com.inlet.ifserver;
import java.util.Arrays;
public class x {
public static void main(String ...args) {
String[] name = {"Alix", "Jack", "Alexis", "Adam", "John", "Lexi",
"George", "Gregory", "Paul", "Bjorn", "Aaron", "Joseph", "Anderson"};
int[] counts = { 3, 3, 2 };
int start = 0;
for (int count : counts) {
int end = Integer.min(start + count, name.length);
if (end == start)
break;
System.out.println(Arrays.toString(Arrays.copyOfRange(name, start, end)));
start = end;
}
if (start < name.length)
System.out.println(Arrays.toString(Arrays.copyOfRange(name, start, name.length)));
}
}
输出:
[Alix, Jack, Alexis]
[Adam, John, Lexi]
[George, Gregory]
[Paul, Bjorn, Aaron, Joseph, Anderson]
TA贡献1824条经验 获得超6个赞
Arrays.copyOfRange的那样是去这里的方式。此示例提供了一个不同块长度的数组,因此它与您问题中的预期输出相匹配。看起来像这样
public static void printInBlocks(String[] arr, int[] blocks) {
int idx = 0;
for (int blockSize: blocks) {
String str = Arrays.toString(Arrays.copyOfRange(name, idx, idx += blockSize));
System.out.println(str);
}
}
然后你可以这样称呼Main它
public static void main(String[] args) {
String[] name = {"Alix", "Jack", "Alexis", "Adam", "John", "Lexi",
"George", "Gregory", "Paul", "Bjorn", "Aaron", "Joseph", "Anderson"};
int[] blocks = {3, 3, 2, 5};
printInBlocks(name, blocks);
}
输出看起来像
[Alix, Jack, Alexis]
[Adam, John, Lexi]
[George, Gregory]
[Paul, Bjorn, Aaron, Joseph, Anderson]
笔记
其中blocks包含每行项目数的总和必须等于项目数name
TA贡献1828条经验 获得超3个赞
您可以手动拆分阵列并使用该copyOfRange方法。
import java.util.Arrays;
public class HelloWorld {
public static void main(String []args){
String[] name = {"Alix", "Jack", "Alexis", "Adam", "John", "Lexi",
"George", "Gregory", "Paul", "Bjorn", "Aaron", "Joseph", "Anderson"};
int splitArrayForSize = 3;
for(int i=0; i< name.length; i+=splitArrayForSize){
String[] subArray = Arrays.copyOfRange(name, i,
Math.min(name.length, i + splitArrayForSize));
String subArrayAsString = Arrays.toString(subArray);
System.out.println(subArrayAsString);
}
}
}
输出:
[Alix, Jack, Alexis]
[Adam, John, Lexi]
[George, Gregory, Paul]
[Bjorn, Aaron, Joseph]
[Anderson]
我确信有一种更简单、更实用的方法来实现这一点。我会对这种方法感兴趣。
添加回答
举报