source

Java 2D 어레이를 인쇄하는 가장 좋은 방법은 무엇입니까?

bestscript 2023. 1. 16. 20:06

Java 2D 어레이를 인쇄하는 가장 좋은 방법은 무엇입니까?

Java에서 2D 어레이를 인쇄하는 가장 좋은 방법은 무엇입니까?

이 코드가 좋은 방법인지 궁금해서요.
그리고 이 코드에서 내가 저지른 다른 실수들도 발견되면.

int rows = 5;
int columns = 3;

int[][] array = new int[rows][columns];

for (int i = 0; i<rows; i++)
    for (int j = 0; j<columns; j++)
        array[i][j] = 0;

for (int i = 0; i<rows; i++) {
    for (int j = 0; j<columns; j++) {
        System.out.print(array[i][j]);
    }
    System.out.println();
}

간단하게 인쇄할 수 있습니다.

아래를 사용하여 2D 어레이를 인쇄

int[][] array = new int[rows][columns];
System.out.println(Arrays.deepToString(array));

아래를 사용하여 1D 어레이를 인쇄

int[] array = new int[size];
System.out.println(Arrays.toString(array));

대체로 더 좋습니다.foreach지수로 산술 연산을 할 필요가 없을 때 말이죠

for (int[] x : array)
{
   for (int y : x)
   {
        System.out.print(y + " ");
   }
   System.out.println();
}

2D 어레이를 심플하고 깔끔하게 인쇄.

System.out.println(Arrays.deepToString(array).replace("], ", "]\n").replace("[[", "[").replace("]]", "]"));

네가 가지고 있는 것에는 아무 문제가 없다.루프를 이중으로 내포하는 것은 코드를 읽는 사람이 쉽게 이해할 수 있습니다.

즉, 다음 공식은 더 조밀하고 관용적인 자바입니다.Arrays나 Collections와 같은 정적 유틸리티 클래스 중 일부를 조만간 찾아보는 것이 좋습니다.효율적인 사용으로 수 톤의 보일러판을 깎을 수 있다.

for (int[] row : array)
{
    Arrays.fill(row, 0);
    System.out.println(Arrays.toString(row));
}

새 라인이 있는 2-라이너:

for(int[] x: matrix)
            System.out.println(Arrays.toString(x));

새 선이 없는 라이너 1개:

System.out.println(Arrays.deepToString(matrix));

그게 최선인 것 같아

   for (int[] row : matrix){
    System.out.println(Arrays.toString(row));
   }
|1 2 3|
|4 5 6| 

다음 코드를 사용하여 값을 인쇄합니다.

System.out.println(Arrays.deepToString());

출력은 다음과 같습니다(한 줄의 전체 매트릭스).

[[1,2,3],[4,5,6]]

Oracle Official Java 8 문서:

public static String deepToString(Object[] a)

지정한 배열의 "상세 내용"에 대한 문자열 표현을 반환합니다.배열에 다른 배열이 요소로 포함되어 있는 경우 문자열 표현에는 해당 내용이 포함됩니다.이 메서드는 다차원 배열을 문자열로 변환하기 위해 설계되었습니다.

스트림과 ForEach를 사용하는 Java 8의 경우:

    Arrays.stream(array).forEach((i) -> {
        Arrays.stream(i).forEach((j) -> System.out.print(j + " "));
        System.out.println();
    });

첫 번째forEach외부 루프로서 동작하는 한편, 다음 루프는 내부 루프로서 동작한다.

System.out.println(Arrays.deepToString(array)
                         .replace("],","\n").replace(",","\t| ")
                         .replaceAll("[\\[\\]]", " "));

불필요한 브래킷을 제거할 수 있습니다..replace(),끝나고.deepToString괜찮으시다면요.다음과 같이 됩니다.

 1  |  2  |  3
 4  |  5  |  6
 7  |  8  |  9
 10 |  11 |  12
 13 |  15 |  15

@Ashika의 답변은 표준 매트릭스 규칙에 따라 (0,0)을 왼쪽 상단 모서리에 표현하고 싶을 때 매우 효과적입니다.그러나 (0,0)을 표준 좌표계 스타일로 왼쪽 아래 모서리에 배치하려는 경우 다음을 사용할 수 있습니다.

LinkedList<String> printList = new LinkedList<String>();
for (char[] row: array) {
    printList.addFirst(Arrays.toString(row));;
}
while (!printList.isEmpty())
    System.out.println(printList.removeFirst());

이것은 LIFO(Last In First Out)를 사용하여 인쇄 시 순서를 바꿉니다.

이거 드셔보세요.

for (char[] temp : box) {
    System.err.println(Arrays.toString(temp).replaceAll(",", " ").replaceAll("\\[|\\]", ""));
}

https://stackoverflow.com/a/49428678/1527469에서 적응(인덱스 추가):

System.out.print(" ");
for (int row = 0; row < array[0].length; row++) {
    System.out.print("\t" + row );
}
System.out.println();
for (int row = 0; row < array.length; row++) {
    for (int col = 0; col < array[row].length; col++) {
        if (col < 1) {
            System.out.print(row);
            System.out.print("\t" + array[row][col]);
        } else {

            System.out.print("\t" + array[row][col]);
        }
    }
    System.out.println();
}
class MultidimensionalArray {
    public static void main(String[] args) {

        // create a 2d array
        int[][] a = {
                {1, -2, 3},
                {-4, -5, 6, 9},
                {7},
        };

        // first for...each loop access the individual array
        // inside the 2d array
        for (int[] innerArray: a) {
            // second for...each loop access each element inside the row
            for(int data: innerArray) {
                System.out.println(data);
            }
        }
    }
}

2D 어레이에서는 이렇게 할 수 있습니다.

언급URL : https://stackoverflow.com/questions/19648240/the-best-way-to-print-a-java-2d-array