我正在尝试从一个具有特定长度的较大的2d数组打印子网格(2d数组),同时从网格上的特定点开始。
例如,这是我的2d数组:
int[][] block = {{2, 4, 5, 6, 5}, {1, 3, 5, 7, 8}, {8, 6, 4, 2, 9}};
假设我希望从1,1点开始或阻止[1] [1]。然后我想从这个较大的2d阵列中打印出2x2网格/盒子。例如,我希望打印出董事会{3,5}& {6,4}。
我想这样做而不需要导入其他类,例如java.util.Arrays。
答案 0 :(得分:0)
public static void main(String[] args) {
int[][] block = {
{2, 4, 5, 6, 5},
{1, 3, 5, 7, 8},
{8, 6, 4, 2, 9}};
printBlock(getGrid(block, 1, 1, 2, 3));
}
public static int[][] getGrid(int[][] block, int x, int y, int w, int h) {
int[][] result = new int[w][h];
int lastX = x + w, lasty = y + h;
for (int i = x; i < lastX; i++) {
for (int j = y; j < lasty; j++) {
result[i - x][j - y] = block[i][j];
}
}
return result;
}
public static void printBlock(int[][] block) {
for (int i = 0; i < block.length; i++) {
for (int b = 0; b < block[i].length; b++) {
System.out.print(block[i][b] + "\t");
}
System.out.println();
}
}
输出:
3 5 7
6 4 2
答案 1 :(得分:0)
您只需要从原始方式更改循环的索引以打印2D数组:
原文:
public static void printSubGrid(int[][] array) {
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++)
System.out.print(array[i][j] + " ");
System.out.println();
}
}
所以使用子网格(属性为xFrom, yFrom, xTo, yTo
)
public static void printSubGrid(int[][] array, int xF, int yF, int xT, int yT) {
for (int i = xF; i < (xF + xT); i++) {
for (int j = yF; j < (yF + yT); j++)
System.out.print(array[i][j] + " ");
System.out.println();
}
}