+ 3
How to assign random numbers in a 2D array matrix ?
Hello guys. I have a homework in java and I have to create a 10x10 matrix and assign random numbers to each element. I could create the matrix and random int part but I could not make it for each element in the matrix. Can someone help please ?
5 Answers
+ 9
Can you show us the code you have been working on? Have you tried using a nested for loop to iterate through the 2D matrix and assign the random numbers manually?
+ 9
You're very close! Instead of storing the random number in a variable and assigning the same number over the matrix, generate and assign the random number on the fly.
for (...)
for (...)
a[x][y] = randomNum.nextInt();
+ 4
Thank you so much sir. I will try when I am available.
+ 3
Random randumNum = new Random();
int s;
s = randomNum.nextInt();
for (int x = 0; x<10; x++){
for(int y = 0; y<10; y++){
a[x][y]=s;
So this is the matrix and random number part of the code, when I do this, the answer is like :
3 3 3
3 3 3
3 3 3
But every element has to be different. I couldnt do it.