我只想创建一个随机布尔2d数组,但它总是返回false ...运算符“&&”的问题?我不明白......
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");
}
}
答案 0 :(得分:4)
我认为您只需要为数组中的每个单元格创建一个新的随机布尔值,如下所示:
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");
}
}
}
答案 1 :(得分:3)
你只计算一次行和col,试试这个:
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");
}
}
答案 2 :(得分:1)
在考虑了你想要的东西之后,这似乎更合理: 对于每一行布尔值和每列一个布尔值,给出:
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();
}
答案 3 :(得分:0)
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");
}
}
}