使用嵌套for循环修改二维阵列



我正在尝试打印出2D数组(a(的"中间"。例如,对于我代码中给定的数组,我想打印:

[3,4,5,6]
[4,5,6,7]

然而,我只能打印出"中间"值。我想修改方法inner中的2D数组(a(,并将其打印到main中,而不是在嵌套的for循环中使用System.out.println。我该怎么做?

这是我的代码:

public static int[][] inner(int[][] a) {
int rowL = a.length - 1;
int colL = a[1].length - 1;
for (int row = 1; row < rowL; row++) {
for (int col = 1; col < colL; col++) {
//System.out.print(a[row][col]);
a = new int[row][col];
}
System.out.println();
}
return a;
}
public static void main(String[] args) {
int[][] a = {
{1, 2, 3, 4, 5, 6},
{2, 3, 4, 5, 6, 7},
{3, 4, 5, 6, 7, 8},
{4, 5, 6, 7, 8, 9}};
for (int[] row : a) {
System.out.println(Arrays.toString(row));
}
System.out.println();
for (int[] row : inner(a)) {
System.out.println(Arrays.toString(row));
}
}

在循环外创建一个新数组,然后通过转换两个数组之间的索引来填充循环内的数组:

public static int[][] inner (int[][] a) {
int rowL = a.length - 1;
int colL = a[1].length -1;
int[][] ret = new int[rowL - 1][colL - 1];
for (int row = 1; row < rowL; row++) {
for (int col = 1; col < colL ; col++) {
ret[row - 1][col - 1] = a[row][col];
}
}
return ret;
}

如果您只想打印中间的值(我对这个代码示例的定义是:middle=完整数组减去第一个和最后一个元素(,您可以使用StringBuilder:

public static void main(String[] args) {
int[][] a = {
{ 1, 2, 3, 4, 5, 6 },
{ 2, 3, 4, 5, 6, 7 },
{ 3, 4, 5, 6, 7, 8 },
{ 4, 5, 6, 7, 8, 9 }
};
for (int[] b : a) {
// create a String output for each inner array
StringBuilder outputBuilder = new StringBuilder();
// append an introducing bracket
outputBuilder.append("[");
// make the values to be printed ignore the first and last element
for (int i = 1; i < b.length - 1; i++) {
if (i < b.length - 2) {
/*
* append a comma plus whitespace 
* if the element is not the last one to be printed
*/
outputBuilder.append(b[i]).append(", ");
} else {
// just append the last one without trailing comma plus whitespace 
outputBuilder.append(b[i]);
}
}
// append a closing bracket
outputBuilder.append("]");
// print the result
System.out.println(outputBuilder.toString());
}
}

输出将是

[2, 3, 4, 5]
[3, 4, 5, 6]
[4, 5, 6, 7]
[5, 6, 7, 8]

您可以使用Arrays.stream(T[],int,int)方法迭代给定范围的数组:

int[][] arr = {
{1, 2, 3, 4, 5, 6},
{2, 3, 4, 5, 6, 7},
{3, 4, 5, 6, 7, 8},
{4, 5, 6, 7, 8, 9}};
int[][] middle = Arrays.stream(arr, 1, arr.length - 1)
.map(row -> Arrays.stream(row, 1, row.length - 1)
.toArray())
.toArray(int[][]::new);
// output
Arrays.stream(middle).map(Arrays::toString).forEach(System.out::println);
[3, 4, 5, 6]
[4, 5, 6, 7]

最新更新