问题描述
我希望能够从我的数组的每一行上打印出数量不等的元素。
String[] name = {"Alix", "Jack", "Alexis", "Adam", "John", "Lexi",
"George", "Gregory", "Paul", "Bjorn", "Aaron", "Joseph", "Anderson"};
System.out.println(Arrays.toString(name));
这样的输出会给我
[Alix, Jack, Alexis, Adam, John, Lexi, George, Gregory, Paul, Bjorn, Aaron, Joseph, Anderson]
但是我希望输出是类似于
[Alix, Jack, Alexis]
[Adam, John, Lexi]
[George, Gregory]
[Paul, Bjorn, Aaron, Joseph, Anderson]
有没有办法做到这一点? 在我的示例中,每行中的元素数量不是固定的,这很重要,因为我可以更改输出中每行中出现的名称的数量。 谢谢
1楼
这是一个示例,可让您为每个列表提供一个大小列表,因此您可以轻松地产生所指示的输出,而不必在每个列表中使用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]
2楼
您可以手动拆分数组,并使用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]
我相信有一种更简单,更实用的方法可以实现这一目标。 我会对这种方法感兴趣。
3楼
正如@Sid提到的, 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