+ 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 ?

4th Nov 2021, 9:30 AM
Güneş Özkan
Güneş Özkan - avatar
5 ответов
+ 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?
4th Nov 2021, 9:34 AM
Hatsy Rei
Hatsy Rei - avatar
+ 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();
4th Nov 2021, 9:51 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
Thank you so much sir. I will try when I am available.
4th Nov 2021, 10:12 AM
Güneş Özkan
Güneş Özkan - avatar
+ 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.
4th Nov 2021, 9:41 AM
Güneş Özkan
Güneş Özkan - avatar