以矩阵格式打印二维数组

发布于 2024-10-18 11:20:02 字数 327 浏览 2 评论 0原文

如何以矩阵框格式打印一个简单的 int[][] ,就像我们手写矩阵的格式一样。简单的循环运行显然不起作用。如果有帮助,我正在尝试在 linux ssh 终端中编译此代码。

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        System.out.println(matrix[i][j] + " ");
    }
    System.out.println();
}

How can I print out a simple int[][] in the matrix box format like the format in which we handwrite matrices in. A simple run of loops doesn't apparently work. If it helps I'm trying to compile this code in a linux ssh terminal.

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        System.out.println(matrix[i][j] + " ");
    }
    System.out.println();
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

心不设防 2024-10-25 11:20:03

要正确设置列中数字的格式,最好使用 printf。根据最大或最小数字的大小,您可能需要调整模式“%4d”。例如,要允许 Integer.MIN_VALUEInteger.MAX_VALUE 之间的任何整数,请使用 "%12d"

public void printMatrix(int[][] matrix) {
    for (int row = 0; row < matrix.length; row++) {
        for (int col = 0; col < matrix[row].length; col++) {
            System.out.printf("%4d", matrix[row][col]);
        }
        System.out.println();
    }
}

输出示例:

 36 913 888 908
732 626  61 237
  5   8  50 265
192 232 129 307

To properly format numbers in columns, it's best to use printf. Depending on how big are the max or min numbers, you might want to adjust the pattern "%4d". For instance to allow any integer between Integer.MIN_VALUE and Integer.MAX_VALUE, use "%12d".

public void printMatrix(int[][] matrix) {
    for (int row = 0; row < matrix.length; row++) {
        for (int col = 0; col < matrix[row].length; col++) {
            System.out.printf("%4d", matrix[row][col]);
        }
        System.out.println();
    }
}

Example output:

 36 913 888 908
732 626  61 237
  5   8  50 265
192 232 129 307
芸娘子的小脾气 2024-10-25 11:20:03
int[][] matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
        {10, 11, 12}
};

printMatrix(matrix);
public void printMatrix(int[][] m) {
    try {
        int rows = m.length;
        int columns = m[0].length;
        String str = "|\t";

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                str += m[i][j] + "\t";
            }
            System.out.println(str + "|");
            str = "|\t";
        }
    } catch (Exception e) {
        System.out.println("Matrix is empty!!");
    }
}

输出:

|   1   2   3   |
|   4   5   6   |
|   7   8   9   |
|   10  11  12  |
int[][] matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},
        {10, 11, 12}
};

printMatrix(matrix);
public void printMatrix(int[][] m) {
    try {
        int rows = m.length;
        int columns = m[0].length;
        String str = "|\t";

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < columns; j++) {
                str += m[i][j] + "\t";
            }
            System.out.println(str + "|");
            str = "|\t";
        }
    } catch (Exception e) {
        System.out.println("Matrix is empty!!");
    }
}

Output:

|   1   2   3   |
|   4   5   6   |
|   7   8   9   |
|   10  11  12  |
岁月打碎记忆 2024-10-25 11:20:03

Java 8中:

import java.util.Arrays;

public class MatrixPrinter {
  public static void main(String[] args) {
    final int[][] matrix = new int[4][4];
    printMatrix(matrix);
  }

  public static void printMatrix(int[][] matrix) {
    Arrays.stream(matrix).forEach((row) -> {
      System.out.print("[");
      Arrays.stream(row).forEach((el) -> System.out.print(" " + el + " "));
      System.out.println("]");
    });
  }
}

这会产生:

[ 0  0  0  0 ]
[ 0  0  0  0 ]
[ 0  0  0  0 ]
[ 0  0  0  0 ]

但是既然我们在这里,为什么不让行布局可定制呢?

我们所需要做的就是将 lamba 传递给 matrixPrinter 方法:

import java.util.Arrays;
import java.util.function.Consumer;

public class MatrixPrinter {
  public static void main(String[] args) {
    final int[][] matrix = new int[3][3];

    Consumer<int[]> noDelimiter = (row) -> {
      Arrays.stream(row).forEach((el) -> System.out.print(" " + el + " "));
      System.out.println();
    };

    Consumer<int[]> pipeDelimiter = (row) -> {
      Arrays.stream(row).forEach((el) -> System.out.print("| " + el + " "));
      System.out.println("|");
    };

    Consumer<int[]> likeAList = (row) -> {
      System.out.print("[");
      Arrays.stream(row).forEach((el) -> System.out.print(" " + el + " "));
      System.out.println("]");
    };

    printMatrix(matrix, noDelimiter);
    System.out.println();
    printMatrix(matrix, pipeDelimiter);
    System.out.println();
    printMatrix(matrix, likeAList);
  }

  public static void printMatrix(int[][] matrix, Consumer<int[]> rowPrinter) {
    Arrays.stream(matrix).forEach((row) -> rowPrinter.accept(row));
  }
}

结果如下:

 0  0  0 
 0  0  0 
 0  0  0 

| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |

[ 0  0  0 ]
[ 0  0  0 ]
[ 0  0  0 ]

In Java 8 fashion:

import java.util.Arrays;

public class MatrixPrinter {
  public static void main(String[] args) {
    final int[][] matrix = new int[4][4];
    printMatrix(matrix);
  }

  public static void printMatrix(int[][] matrix) {
    Arrays.stream(matrix).forEach((row) -> {
      System.out.print("[");
      Arrays.stream(row).forEach((el) -> System.out.print(" " + el + " "));
      System.out.println("]");
    });
  }
}

This produces:

[ 0  0  0  0 ]
[ 0  0  0  0 ]
[ 0  0  0  0 ]
[ 0  0  0  0 ]

But since we are here why not make the row layout customisable?

All we need is to pass a lamba to the matrixPrinter method:

import java.util.Arrays;
import java.util.function.Consumer;

public class MatrixPrinter {
  public static void main(String[] args) {
    final int[][] matrix = new int[3][3];

    Consumer<int[]> noDelimiter = (row) -> {
      Arrays.stream(row).forEach((el) -> System.out.print(" " + el + " "));
      System.out.println();
    };

    Consumer<int[]> pipeDelimiter = (row) -> {
      Arrays.stream(row).forEach((el) -> System.out.print("| " + el + " "));
      System.out.println("|");
    };

    Consumer<int[]> likeAList = (row) -> {
      System.out.print("[");
      Arrays.stream(row).forEach((el) -> System.out.print(" " + el + " "));
      System.out.println("]");
    };

    printMatrix(matrix, noDelimiter);
    System.out.println();
    printMatrix(matrix, pipeDelimiter);
    System.out.println();
    printMatrix(matrix, likeAList);
  }

  public static void printMatrix(int[][] matrix, Consumer<int[]> rowPrinter) {
    Arrays.stream(matrix).forEach((row) -> rowPrinter.accept(row));
  }
}

This is the result:

 0  0  0 
 0  0  0 
 0  0  0 

| 0 | 0 | 0 |
| 0 | 0 | 0 |
| 0 | 0 | 0 |

[ 0  0  0 ]
[ 0  0  0 ]
[ 0  0  0 ]
白云悠悠 2024-10-25 11:20:03
int[][] matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
};
//use foreach loop as below to avoid IndexOutOfBoundException
//need to check matrix != null if implements as a method
//for each row in the matrix
for (int[] row : matrix) {
    //for each number in the row
    for (int j : row) {
        System.out.print(j + " ");
    }
    System.out.println("");
}
int[][] matrix = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
};
//use foreach loop as below to avoid IndexOutOfBoundException
//need to check matrix != null if implements as a method
//for each row in the matrix
for (int[] row : matrix) {
    //for each number in the row
    for (int j : row) {
        System.out.print(j + " ");
    }
    System.out.println("");
}
飘落散花 2024-10-25 11:20:03
public static void printMatrix(double[][] matrix) {
    for (double[] row : matrix) {
        for (double element : row) {
            System.out.printf("%5.1f", element);
        }
        System.out.println();
    }
}

函数调用

printMatrix(new double[][]{2,0,0},{0,2,0},{0,0,3}});

输出

  2.0  0.0  0.0
  0.0  2.0  0.0
  0.0  0.0  3.0

控制台中的

控制台输出

public static void printMatrix(double[][] matrix) {
    for (double[] row : matrix) {
        for (double element : row) {
            System.out.printf("%5.1f", element);
        }
        System.out.println();
    }
}

Function Call

printMatrix(new double[][]{2,0,0},{0,2,0},{0,0,3}});

Output

  2.0  0.0  0.0
  0.0  2.0  0.0
  0.0  0.0  3.0

In console

Console Output

呆萌少年 2024-10-25 11:20:03

自 Java 8 起:

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

Arrays.stream(matrix).map(Arrays::toString).forEach(System.out::println);

输出:

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

Since Java 8:

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

Arrays.stream(matrix).map(Arrays::toString).forEach(System.out::println);

Output:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
梦冥 2024-10-25 11:20:03

这是我使用 StringBuilder 数组显示 2D 整数数组的有效方法。

public static void printMatrix(int[][] arr) {
    if (null == arr || arr.length == 0) {
        // empty or null matrix
        return;
    }

    int idx = -1;
    StringBuilder[] sbArr = new StringBuilder[arr.length];

    for (int[] row : arr) {
        sbArr[++idx] = new StringBuilder("(\t");

        for (int elem : row) {
            sbArr[idx].append(elem + "\t");
        }

        sbArr[idx].append(")");
    }

    for (int i = 0; i < sbArr.length; i++) {
        System.out.println(sbArr[i]);
    }
    System.out.println("\nDONE\n");
}

输出:

(   1   2   3   )
(   4   5   6   )
(   7   8   9   )
(   10  11  12  )

DONE

Here's my efficient approach for displaying 2D integer array using a StringBuilder array.

public static void printMatrix(int[][] arr) {
    if (null == arr || arr.length == 0) {
        // empty or null matrix
        return;
    }

    int idx = -1;
    StringBuilder[] sbArr = new StringBuilder[arr.length];

    for (int[] row : arr) {
        sbArr[++idx] = new StringBuilder("(\t");

        for (int elem : row) {
            sbArr[idx].append(elem + "\t");
        }

        sbArr[idx].append(")");
    }

    for (int i = 0; i < sbArr.length; i++) {
        System.out.println(sbArr[i]);
    }
    System.out.println("\nDONE\n");
}

Output:

(   1   2   3   )
(   4   5   6   )
(   7   8   9   )
(   10  11  12  )

DONE
毁梦 2024-10-25 11:20:03
public class Matrix {
    public static void main(String[] args) {
        double Matrix[][] = {
                {0*1, 0*2, 0*3, 0*4},
                {0*1, 1*1, 2*1, 3*1},
                {0*2, 1*2, 2*2, 3*2},
                {0*3, 1*3, 2*3, 3*3}};

        int i, j;
        for (i = 0; i < 4; i++) {
            for (j = 0; j < 4; j++)
                System.out.print(Matrix[i][j] + " ");
            System.out.println();
        }
    }
}

输出:

0.0 0.0 0.0 0.0 
0.0 1.0 2.0 3.0 
0.0 2.0 4.0 6.0 
0.0 3.0 6.0 9.0 
public class Matrix {
    public static void main(String[] args) {
        double Matrix[][] = {
                {0*1, 0*2, 0*3, 0*4},
                {0*1, 1*1, 2*1, 3*1},
                {0*2, 1*2, 2*2, 3*2},
                {0*3, 1*3, 2*3, 3*3}};

        int i, j;
        for (i = 0; i < 4; i++) {
            for (j = 0; j < 4; j++)
                System.out.print(Matrix[i][j] + " ");
            System.out.println();
        }
    }
}

Output:

0.0 0.0 0.0 0.0 
0.0 1.0 2.0 3.0 
0.0 2.0 4.0 6.0 
0.0 3.0 6.0 9.0 
§普罗旺斯的薰衣草 2024-10-25 11:20:03

我更喜欢在 Java 中使用增强循环

,因为我们的 ar 是一个数组的数组 [2D]。因此,当您对其进行迭代时,您将首先获得一个数组,然后您可以迭代该数组以获取各个元素。

public static void main(String[] args) {
    int[][] ar = {
            {12, 33, 23},
            {34, 56, 75},
            {14, 76, 89},
            {45, 87, 20}};

    for (int[] num : ar) {
        for (int ele : num) {
            System.out.print(" " + ele);
        }
        System.out.println(" ");
    }
}

输出:

 12 33 23 
 34 56 75 
 14 76 89 
 45 87 20 

I prefer using enhanced loop in Java

Since our ar is an array of array [2D]. So, when you iterate over it, you will first get an array, and then you can iterate over that array to get individual elements.

public static void main(String[] args) {
    int[][] ar = {
            {12, 33, 23},
            {34, 56, 75},
            {14, 76, 89},
            {45, 87, 20}};

    for (int[] num : ar) {
        for (int ele : num) {
            System.out.print(" " + ele);
        }
        System.out.println(" ");
    }
}

Output:

 12 33 23 
 34 56 75 
 14 76 89 
 45 87 20 
夜夜流光相皎洁 2024-10-25 11:20:02
final int[][] matrix = {
  { 1, 2, 3 },
  { 4, 5, 6 },
  { 7, 8, 9 }
};

for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}

生产:

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

for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + " ");
    }
    System.out.println();
}

Produces:

1 2 3
4 5 6
7 8 9
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文