簡體   English   中英

如何從 4X4 數組中僅打印 2X2 數組

[英]How to print only 2X2 array from 4X4 array

我是 Java 編程的新手。 我正在使用 arrays,我只想從 4X4 陣列打印 2X2 陣列。

例子:

int a[][]= {{2,4,6,8},
            {1,3,5,7},
            {1,2,3,4},
            {0,9,8,7}};

使用下面的代碼,我可以打印數組中的所有數字。

for(int i[]:a) {
    for(int j:i) {
        System.out.println(j + "");
    }
}

但是,我只想打印3,4,8,7 (右下角 2X2 數組)。 我該怎么做?

這可以通過使用正常的 for 循環來完成。 您正在使用的基於集合的 for-each 循環將始終遍歷集合中的所有對象。 如果您只想遍歷數組的某個范圍,請使用普通的 for 循環並遍歷您關注的索引。

for (int i = 2; i < 4; i++) {
    for (int j = 2; j < 4; j++) {
        System.out.println("" + a[i][j]);
    }
}

讓我們有一個 x 和 y 偏移,並打印一個定義的寬度和高度:

int offset_x = 2;
int offset_y = 2;
int width = 2;
int height = 2;

for (int y = offset_y; y >= 0 &&  y < offset_y + height && y < a.length; y++) {
    for (int x = offset_x; x >= 0 && x < offset_x + width && x < a[y].length; x++) {
        System.out.print(a[y][x]+",");
    }
    System.out.println();
}

在此設置中,它將從 2,2 開始打印 2x2,但您可以調整值以在 0,1 處打印 3x3。 它受到保護,不會超出數組的末尾,如果使用負索引,它不會打印

你可以形象化

2 4 6 8
1 3 5 7
1 2 3 4
0 9 8 7

這組數字為

[0,0] [0,1] [0,2] [0,3]
[1,0] [1,1] [1,2] [1,3]
[2,0] [2,1] [2,2] [2,3]
[3,0] [3,1] [3,2] [3,3]

括號中的第一個數字代表行,而第二個數字代表列。

了解到這一點,我們現在得到 position 或您要打印的數字的索引。

[2,2] [2,3]
[3,2] [3,3]

從你給定的一組數字中,我得到他們的行和列索引,然后分析一個更好的 for 循環解決方案來打印你的問題。

for (int row = 2; row < 4; row++) {
    for (int col = 2; col < 4; col++) {
          System.out.println(a[row][col]) ;
    } 
}

上面的解決方案與此沒有什么不同:

System.out.println(a[2][2]);
System.out.println(a[2][3]);
System.out.println(a[3][2]);
System.out.println(a[3][3]);

為了打印一系列索引中的元素,您需要使用嵌套循環來瀏覽該范圍內的索引。 執行以下操作:

public class Main {
    public static void main(String[] args) {
        int a[][] = { 
                { 2, 4, 6, 8 }, 
                { 1, 3, 5, 7 }, 
                { 1, 2, 3, 4 }, 
                { 0, 9, 8, 7 } };
        for (int i = a.length / 2; i < a.length; i++) {
            for (int j = a[i].length / 2; j < a[i].length; j++) {
                System.out.print(a[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Output:

3 4 
8 7 

在這里,如果我們將二維數組視為表格,則您要查找的索引范圍是從row#2 to 3和從column#2 to 3

請注意,索引從數組中的0開始。 此外,二維陣列是一維 arrays 的陣列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM