Нужно печатать строки многомерного массива в виде столбцов - PullRequest
0 голосов
/ 11 июня 2019

Это вывод моей программы:

Enter the size of 2D array: 
4
1   2   3   4   

5   6   7   8   

9   10  11  12  

13  14  15  16

, и мне нужно это вместо этого:

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

Я хочу, чтобы 2d-массив имел размер NxN, где n - целое число, введенноеПользователь.Я хочу, чтобы первые последовательные значения сохранялись в четных индексированных столбцах сверху вниз, а следующие последовательные значения сохранялись в нечетных индексированных столбцах снизу вверх.

import java.util.Scanner;

public class Lab6 {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the size of 2D array: ");
    System.out.println();
    int n = input.nextInt();

    int arr[][] = new int[n][n];

    int inc=1;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<n;j++)
        {
        arr[i][j]=inc;
        inc++;
        }
    }

    transpose(arr);

    // now let's print a two dimensional array in Java
    for (int[] a : arr) {
        for (int i : a) {
            System.out.print(i + "\t");
        }
        System.out.println("\n");

    }
}
public static int[][] transpose (int[][] array) {
      if (array == null || array.length == 0)//empty or unset array, nothing do to here
        return array;

      int width = array.length;
      int height = array[0].length;

      int[][] array_new = new int[height][width];

      for (int x = 0; x < width; x++) {
        for (int y = 0; y < height; y++) {
          array_new[y][x] = array[x][y];
        }
      }
      return array_new;
    }
}

Ответы [ 2 ]

2 голосов
/ 11 июня 2019

Как указал Шон в комментариях, ваша функция transpose() возвращает новый массив, но вы его не захватываете и не используете. Исходный массив остается неизменным, что и отображается в конце.

Изменение:

transpose(arr);

// now let's print a two dimensional array in Java
for (int[] a : arr) {

Кому:

int[][] newArr = transpose(arr);

// now let's print a two dimensional array in Java
for (int[] a : newArr) {
1 голос
/ 11 июня 2019

Попробуйте это.Он должен делать то, что вы описали в вопросе.

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.print("Enter the size of 2D array: ");
    System.out.println();
    int n = input.nextInt();
    int arr[][] = new int[n][n];

    int inc=1;
    for(int j = 0; j < n; j += 2) {
        for(int i = 0; i < n; i++) {
            arr[i][j]=inc++;
        }
    }
    for(int j = 1; j < n; j += 2) {
        for(int i = n - 1; i >= 0; i--) {
            arr[i][j]=inc++;
        }
    }

    // now let's print a two dimensional array in Java
    for (int[] a : arr) {
        for (int i : a) {
            System.out.print(i + "\t");
        }
        System.out.println();
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...