【问题标题】:Filling boolean [ ][ ] best way填充 boolean [ ][ ] 最佳方式
【发布时间】:2018-04-24 07:34:59
【问题描述】:

我正在使用它而不是 BitSet 进行练习。我想创建不同的数组并为相交、联合等创建自己的方法。 我还希望能够打印布尔数组,这样我就知道发生了什么。感谢您的帮助。

步骤 1. 创建私有静态方法,用不同的值填充 nxm 布尔数组。 2. 创建新数组并调用方法fillArray(myArray, int row, int col)。 3. 打印数组。

        boolean[][] myArray= new boolean[][];
        fillArray(myArray);



    }

    public static boolean[][] fillArray(boolean[][] bArray, int row, int col) {
        bArray = new boolean[row][col];
        Random rand = new Random();

        for(int i=0; i<row;i++) {
            bArray[i][0] = rand.nextBoolean();
            for(int j=0; j<col;j++) {
                bArray[j][0] = rand.nextBoolean();
            }
        }
        return bArray;
    }

}

【问题讨论】:

标签: java boolean discrete-mathematics


【解决方案1】:

我会像这样重写你的 fill 方法:

public static boolean[][] fillArray(int row, int col, Random rand) {
    boolean[][] bArray = new boolean[row][col];
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < col; j++) {
            bArray[i][j] = rand.nextBoolean();
        }
    }
    return bArray;
}

注意事项:

  1. 我已将Random 实例作为参数传递,因为使用随机种子创建新的Random 实例成本很高。 (提示:您需要从操作系统获取随机种子。
  2. 我已删除 bArray 参数,因为您实际上忽略了它。
  3. 我已经修复了嵌套循环...这是完全错误的。

或者

public static boolean[][] fillArray(boolean[][] bArray, Random rand) {
    for (int i = 0; i < bArray.length; i++) {
        for (int j = 0; j < bArray[i].length; j++) {
            bArray[i][j] = rand.nextBoolean();
        }
    }
    return bArray;
}

这会填充您已经创建并提供的整个数组。

【讨论】:

    【解决方案2】:

    您必须为数组指定行和列的大小。尝试类似:

    public static void main(String[] args) {
        int row = 10;
        int col = 10;
        boolean[][] myArray= new boolean[row][col];
        fillArray(myArray, row, col);
    
        for(boolean[] row1: myArray){
            printRow(row1);
        }
    
    }
    
    public static boolean[][] fillArray(boolean[][] bArray, int row, int col) {
        Random rand = new Random();
    
        for(int i=0; i<row;i++) {
            for(int j=0; j<col;j++) {
                bArray[i][j] = rand.nextBoolean();
            }
        }
        return bArray;
    }
    
    public static void printRow(boolean[] row) {
        for (boolean i : row) {
            System.out.print(i);
            System.out.print("\t");
        }
        System.out.println();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 1970-01-01
      • 1970-01-01
      • 2019-03-29
      • 2018-07-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多