I want to randomly generate a symmetrical 10x10 table with "*" symbols but It all basically prints in two long rows. I know I'm doing something wrong but I'm looking at it too hard and cant see the issue.
public class Main {
public static void main(String[]args) {
int n = 10;
char[][] array = new char[n][n];
Random rd = new Random();
for(int i = 0; i < n; i ) {
for(int j = 0; j < i; j ) {
char value;
if (Math.random()> .5) {
value = '*';
}
else {
value = ' ';
}
array[i][j] = value;
array[j][i] = value;
System.out.print(array[i][j]);
System.out.println();
System.out.print(array[j][i]);
}
}
}
}```
CodePudding user response:
I don't see your context here. But you can try this
public class Main {
public static void main(String[] args) {
int n = 10;
char[][] array = new char[n][n];
for (int i = 0; i < n; i ) {
for (int j = 0; j < i; j ) {
char value;
if (Math.random() > .5) {
value = '*';
} else {
value = ' ';
}
array[i][j] = value;
System.out.print(array[i][j]);
}
System.out.println();
}
}
}
CodePudding user response:
you're not printing row by row, also missing the diagonal element. Fixing those and some other minor changes
int n = 10;
char[][] matrix = new char[n][n];
Random rd = new Random();
for(int i = 0; i < n; i ) {
for(int j = 0; j <= i; j ) {
char value = rd.nextBoolean() ? '*':' ';
matrix[i][j] = value;
matrix[j][i] = value;
}
}
for(char[] row : matrix) {
System.out.println(row);
}