Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何打印特定列中的值_Java - Fatal编程技术网

Java 如何打印特定列中的值

Java 如何打印特定列中的值,java,Java,所以我想知道如何从一个给定的数组中打印一个特定的列,我完全被卡住了。 我设法打印了整个矩阵,但没有在特定列上打印 这是给学校的 public class ex_1 { public static void main(String[] args) { int[][] arr = {{-1, -1, 1, 2, 3, -1}, {-1, 4, 5, 1, -1, -1}, {-1, -1, 6, 5, 4, 3

所以我想知道如何从一个给定的数组中打印一个特定的列,我完全被卡住了。 我设法打印了整个矩阵,但没有在特定列上打印

这是给学校的

public class ex_1 {
    public static void main(String[] args) {

        int[][] arr = {{-1, -1, 1, 2, 3, -1},
                {-1, 4, 5, 1, -1, -1},
                {-1, -1, 6, 5, 4, 3},
                {-1, 2, 5, 3},
                {1, 2, 1}};

        getNumFromCol(arr, 1);
    }

    public static int getNumFromCol(int[][] mat, int col) {
        int temp = 0;
        for (int i = 0; i < mat.length; i++) {
            for (int j = 0; j < mat[i].length; j++) {
                if (mat[i][j] != -1) {
                    temp = mat[col][j];
                }
            }
            System.out.print(temp);
        }
        return temp;
    }
}
422当访问2D数组矩阵时,需要给出矩阵[i][j],其中i是行号,j是列号

因此,如果要打印某个列的列,则需要在矩阵中每行的列位置处打印该项。它将如下所示:

public static void printColumn(int[][] matrix, int col) {
    for (int[] row: matrix) {
        System.out.println(row[col]);
    }
}
笔记 如果希望列的格式美观,可以使用逐步构建输出。例如,如果您希望列的格式像[1,2,3,4,5],它将如下所示

public static void printColumn(int[][] matrix, int col) {
    StringBuilder sb = new StringBuilder();
    sb.append("[ ");

    for (int[] row: matrix) {
        sb.append(row[col]).append(' ');
    }

    sb.append(']');

    System.out.println(sb.toString());
}

首先,你不需要做嵌套循环。如果你想在整个矩阵上迭代,那么你需要嵌套循环——一个用于X,一个用于Y,但是既然你已经知道了列,那么一个循环就足够了

    for (int j = 0; j < mat[col].length; j++) {
        temp = mat[col][j];
        System.out.println(temp);
    }
可能的副本和另一个副本: