I am trying to create a 3x3 matrix that has the numbers 1 to 9 generated at different locations each time you run the code. the method I came up with does not work and I can't find out why it doesn't work, so if anyone could point out the reason why it does not work it would be really really appreciated.
and if anyone knows how to solve this problem in any other way please let me know.
Here's the method I created:
public static int[][] randgen() {
Random rand = new Random();
int[][] a = new int[3][3];
int x;
for(int i = 0; i<a.length; i++) {
for (int j = 0; j < a.length; j++) {
a[i][j] = rand.nextInt(8) +1;
do {
x = 1;
for(int k = 0; k<i; k++) {
for(int l = 0; l<j; l++) {
if(a[k][l] == a[i][j]) {
x++;
}
}
}
if(x!=1) {
a[i][j] = rand.nextInt(8) +1;
}
} while (x!=1); //this while loop I'm using as a way to find duplicates and keep changing up the number until I reach an integer with no duplicates, and this is the part of the program that is failing and I can't understand why
}
}
}
I've tried creating a sorted algorithm and then making a function to shuffle some of the elements which also did not work.
The only thing that worked for me is creating an ArrayList and then printing it out in a way that it looks like an array