loukios
loukios

Reputation: 245

Random boolean 2d-array in Java returning always "false"

I just wanted to create a random boolean 2d-array but it always returns false...A problem with the operator "&&"? I don't get it...

public static void main(String[] args){

    boolean[][] arr = new boolean[5][5];
    Random r = new Random();
    boolean row = r.nextBoolean();
    boolean col = r.nextBoolean();

    for(int i=0 ; i<arr.length ; i++){

        for(int j=0;j<arr[i].length;j++){

        arr[i][j] = row && col;

        System.out.print(arr[i][j]+"\t");

    }

}

Upvotes: 1

Views: 607

Answers (4)

dkero
dkero

Reputation: 121

Here is compiled and working JAVA solution


/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
    public static void main (String[] args) throws java.lang.Exception
    {
        boolean[][] arr = new boolean[5][5];
        int cnt = 0;

        for(int i = 0; i < arr[i].length; i++)
        {
            for(int j = 0; j < arr[i].length; j++)
            {
                Random r = new Random();
                boolean row = r.nextBoolean();
                boolean col = r.nextBoolean();
                arr[i][j] = row && col;
                System.out.print(arr[i][j]+"\t");
            }
        }
}

Upvotes: 0

ctst
ctst

Reputation: 1680

After thinking of what you might want, this seems more plausible: For every row a boolean and for every column a boolean, giving this:

int columns =5;
int rows =5;
boolean[][] arr = new boolean[rows][columns];
Random r = new Random();
boolean[] row = new boolean[rows];
boolean[] col = new boolean[columns];

for(int i=0; i<rows; i++){
    row[i] = r.nextBoolean();
}
for(int i=0; i<columns; i++){
    col[i] = r.nextBoolean();
}

for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr[i].length; j++) {
        arr[i][j] = row[i] && col[j];
        System.out.print(arr[i][j] + "\t");
    }
    System.out.println();
}

Upvotes: 1

umbungo_wine
umbungo_wine

Reputation: 79

I think all you want is to create a new random boolean for each cell in the array like this:

public static void main(String[] args){

    boolean[][] arr = new boolean[5][5];
    Random r = new Random();

    for(int i = 0; i < arr.length; i++){
        for(int j = 0; j < arr[i].length; j++){

            arr[i][j] = r.nextBoolean();

            System.out.print(arr[i][j]+"\t");
        }
    }   
}

Upvotes: 4

ctst
ctst

Reputation: 1680

You only calculate row and col once, try this instead:

boolean[][] arr = new boolean[5][5];
Random r = new Random();
boolean row;
boolean col;

for (int i = 0; i < arr.length; i++) {
    for (int j = 0; j < arr[i].length; j++) {
        row = r.nextBoolean();
        col = r.nextBoolean();
        arr[i][j] = row && col;
        System.out.print(arr[i][j] + "\t");
    }
}

Upvotes: 3

Related Questions