การพิมพ์อาร์เรย์ 2 มิติในรูปแบบเมทริกซ์

ฉันจะพิมพ์ 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();
}

person dawnoflife    schedule 21.02.2011    source แหล่งที่มา


คำตอบ (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();
}

ผลิต:

1 2 3
4 5 6
7 8 9
person Tyler Treat    schedule 21.02.2011

หากต้องการจัดรูปแบบตัวเลขในคอลัมน์ให้เหมาะสม ควรใช้ printf ขึ้นอยู่กับว่าตัวเลขสูงสุดหรือต่ำสุดมีขนาดใหญ่เพียงใด คุณอาจต้องการปรับรูปแบบ "%4d" ตัวอย่างเช่น หากต้องการอนุญาตให้ใช้จำนวนเต็มระหว่าง Integer.MIN_VALUE ถึง Integer.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
person stivlo    schedule 02.08.2014

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  |
person Yuuta    schedule 21.02.2011

ในรูปแบบ 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 ]
person Dalen    schedule 02.10.2016

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

ในคอนโซล

เอาต์พุตคอนโซล

person Denys Vitali    schedule 26.04.2017

ตั้งแต่ 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]
person Community    schedule 12.06.2021

ต่อไปนี้เป็นแนวทางที่มีประสิทธิภาพของฉันในการแสดงอาร์เรย์จำนวนเต็ม 2D โดยใช้อาร์เรย์ StringBuilder

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
person Devendra Lattu    schedule 01.04.2017

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 
person ajit kumar    schedule 02.03.2013

ฉันชอบใช้การวนซ้ำที่ปรับปรุงใน Java

เนื่องจาก ar ของเราเป็น อาร์เรย์ของอาร์เรย์ [2D] ดังนั้น เมื่อคุณวนซ้ำ คุณจะได้อาร์เรย์ก่อน จากนั้นคุณสามารถวนซ้ำ array นั้นเพื่อรับองค์ประกอบแต่ละรายการ

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 
person Vishwa Ratna    schedule 26.05.2018