Вопрос-ответ

The best way to print a Java 2D array? [closed]

Лучший способ распечатать 2D-массив Java?

Мне было интересно, какой лучший способ печати 2D-массива на Java?

Мне просто интересно, является ли этот код хорошей практикой или нет?
Также любые другие ошибки, которые я допустил в этом коде, если вы их обнаружите.

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();
}
Переведено автоматически
Ответ 1

Вы можете печатать простым способом.

Используйте приведенное ниже для печати 2D-массива

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

Используйте приведенное ниже для печати одномерного массива

int[] array = new int[size];
System.out.println(Arrays.toString(array));
Ответ 2

Я бы предпочел, как правило, foreach когда мне не нужно выполнять арифметические операции с их индексами.

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

Simple and clean way to print a 2D array.

System.out.println(Arrays.deepToString(array).replace("], ", "]\n").replace("[[", "[").replace("]]", "]"));
Ответ 4

There is nothing wrong with what you have. Double-nested for loops should be easily digested by anyone reading your code.

That said, the following formulation is denser and more idiomatic java. I'd suggest poking around some of the static utility classes like Arrays and Collections sooner than later. Tons of boilerplate can be shaved off by their efficient use.

for (int[] row : array)
{
Arrays.fill(row, 0);
System.out.println(Arrays.toString(row));
}
2024-02-29 06:56 java arrays