0

I haven't used 2D Arrays before so apologies for any 'obvious statements'. I want to create a 2D Array for a 15 by 20 'table' and want the following to be applied:

  • I want each row to be a separate Array.
  • I want each row to have random 0's and 1's generated

The code I have created creates the 15 x 20 table but not sure if each row is an Array and can't figure out how to put random 0's and 1's. Help would be appreciated! Thanks!

    for (int i=0; i < ar.length; i++) {
    for (int j=0; j < ar[i].length; j++) {
        ar[i][j] = 0;
        System.out.print(" " + ar[i][j]);
    }
    System.out.println("");
    }

2 Answers 2

2

Like this?

int cols = 15;
int rows = 20;

Random rand = new Random();

int[][] myArray = new int[rows][cols];

for (int i=0; i < myArray.length; i++) {
    for (int j=0; j < myArray[i].length; j++) {
        myArray[i][j] = rand.nextInt(2);
        System.out.print(" " + myArray[i][j]);
    }
    System.out.println("");
}

Read more here

Sign up to request clarification or add additional context in comments.

2 Comments

Oh that was simple. Cheers for the help!
I managed to change it so it showed random number from 1 to 10, which I want. But I want to know how do I limit the number of times as number appear, to 4??
1

Use nextInt method.

myArray[i][j] = rand.nextInt(2); // we are using 2 cause nextInt generates random number between 0 to 2 exclusive.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.