Answer the question
In order to leave comments, you need to log in
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
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;
}
}
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();
}
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" // побочная диагональ
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question