java - 使用嵌套的 for 循环修改二维数组
问题描述
我正在尝试打印出二维数组 (a) 的“中间”。例如,对于我的代码中的给定数组,我想打印:
[3,4,5,6]
[4,5,6,7]
但是我只能打印出“中间”值。我想修改方法 inner 中的二维数组 (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;
}
推荐阅读
- python - Python Excel Pandas Loop 不会中断
- javascript - Photoshop,用于查找图层名称中包含单词的图层的脚本
- python-3.x - Python 扩展无法找到正确的调试文件夹
- css - 样式 css 不适用于 module.css
- r - 使用R中的循环附加每n列
- google-apps-script - 如何在一天中的特定时间锁定 Google 工作表
- javascript - VSCode 没有正确导入我的 main.js 文件
- python - 如何使用硒发送多行文本
- javascript - 没有某些属性的悬挂点
- xamarin.forms - SkiaSharp:ArcTo() 和 Close() 的意外结果