How do I randomly fill an array in Java?
Posted
by Kat
on Stack Overflow
See other posts from Stack Overflow
or by Kat
Published on 2010-03-23T00:40:51Z
Indexed on
2010/03/23
0:51 UTC
Read the original article
Hit count: 349
I'm writing a program that creates a 2D array from a integer n. I then have to fill the array with values from 1 to the n*n array size and check to see if it is a magic square. The way I am doing it now fills the array in order from 1 to n*n array size. How can I make that random?
My code:
System.out.print("Enter an whole number: ");
int n = scan.nextInt();
int [][] magic = new int [n][n];
for (int row = 0; row < magic.length; row++)
{
for(int col = 0; col < magic[row].length; col++)
magic[row][col] = ((row * n) + 1) + col;
}
© Stack Overflow or respective owner