A
A
agenda_nati2020-04-09 11:31:39
Java
agenda_nati, 2020-04-09 11:31:39

How to properly populate a multidimensional array?

Everything went smoothly, until one day the task fell on me to draw one big X out of Xs. I was able to do it through a loop, but the teacher told me to try using a multidimensional array in this task, after which I was completely confused.

class Loader {

    public static void main(String[] args) {


        int size = 7;

        String [] [] array = new String[size-1][size-1];


        for (int i = 1; i < size; i++) {
            for (int j = 1; j < size; j++) {
              .// заполнить массив
            }
        }


        for (int i = 1; i < size; i++) {
            for (int j = 1; j < size; j++) {
               // распечатать массив
            }
        }
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Koshkasobaka, 2020-04-09
@agenda_nati

I don't understand why when declaring an array you specify its size as [size-1][size-1], do you need an array of 6x6 or 7x7? In my example it will be 7x7. You don’t need String as variables, you only need one character, so it’s better to use
char

char[][] array = new char[size][size];
        char tic = 'x';
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array.length; j++) {
                if (j == i || j == array.length - 1 - i)
                    array[i][j] = tic;
            }
        }

We display it in the form of a matrix:
for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                System.out.print(array[i][j] + " ");
            }
            System.out.println();
        }

A
ads83, 2020-04-09
@ads83

In a two-dimensional array, "X" is the two large diagonals. You can fill them without nested loops:

public void fillX(String[][] array) {
  for (int i=1; i<size; i++) {
    array[i][i] = "x" // главная диагональ
    array[i][size-i] = "x" // побочная диагональ
  }
}

Get used to using methods, it will come in handy pretty soon.
With the output, everything is simple: we use print in the nested loop so that there is no transition to a new line, and println without parameters to start a new line in the outer loop.
I intentionally do not write code, but describe it in words so that you have the opportunity to write it yourself and practice.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question