[英]Printing elements from array in specific format
我有以下两个数组
int a[]={1,2,3,4,5,6,7,8,9};
int b[]={4,2,3}
输出应为
b[0] has 4 so the first line of output should be 1,2,3,4 (from array a )
b[1] has 2 so the 2nd line of output should be 5,6 (from array a )
b[2] has 3 so the 3rd line of outout should be 7,8,9 (from array a )
输出应该是这样的
1,2,3,4
5,6
7,8,9
我正在尝试使用此代码,但无法正常工作
for(i=0;i<b[j];i++)
{
if(flag==false){
System.out.print(a[i]);
flag=true;
}
else
System.out.print(" "+a[i]);
}
j=j+1;
System.out.print("\n");
注意:数组a
和b
可以有任意数量的元素
int cur = 0; //denotes index of array a
for (int i=0; i<b.length; i++) { //looping on the elements of b
int count = b[i], j; //count: number of elements to print is in b[i]
for(j=cur; j<cur+count && j<a.length; j++) //looping from current index in array a to the next "count" elements which we need to print
System.out.print(a[j]+","); //print the elements for one line
System.out.println();
cur = j; //updating the new index of array a from where to start printing
}
通过将b[]
元素的运行总计保存在整数变量nextIndex
,我们跟踪在a[]
到达哪个索引。
注意:该代码起作用的前提条件是b[]
的元素总和不得大于a[]
的元素数。
public static void main(String[] args) {
int[] a = { 1,2,3,4,5,6,7,8,9 };
int[] b = { 4,2,3 };
int nextIndex = 0;
for (int i = 0; i < b.length; i++) {
for (int j = nextIndex; j < nextIndex + b[i]; j++) {
if (j == (nextIndex + b[i] - 1)) {
System.out.print(a[j]);
}
else {
System.out.print(a[j] + ",");
}
}
nextIndex += (b[i]);
System.out.println();
}
}
当使用Arrays.copyOfRange(int[] original, int from, int to)
从原始数组中提取“子”数组时,一个for循环足以完成您想要的Arrays.copyOfRange(int[] original, int from, int to)
。 Arrays.toString()
为您打印阵列。
public static void main(String[] args) throws Exception {
int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int b[] = {4, 2, 3};
int aIndex = 0;
int bIndex = 0;
for (int i = 0; i < b.length; i++) {
bIndex += b[i]; // Keeps track of the ending index of the copying
System.out.println(Arrays.toString(Arrays.copyOfRange(a, aIndex, bIndex)));
aIndex += b[i]; // Keeps track of the starting index of the copying
}
}
结果:
[1, 2, 3, 4]
[5, 6]
[7, 8, 9]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.