Java获取10个布尔值并将其随机化



这是我的第一篇文章,如果我做错了什么,很抱歉!

我正在尝试制作一个程序,你可以输入宽度和高度。从这两个值中,取其中的10个,并将这10个值随机设置为true或false。顺便说一句,这是我一直遇到麻烦的学校作业。

我该怎么做?

这是给我的问题:

任务1:

  1. 创建新类"BinaryMap">
  2. 创建新方法";generateRandomArray Fix";它创建了一个大小为10x10的2D布尔数组
  3. 用false初始化所有值
  4. 100个值中的10个应随机更改为true
  5. 返回布尔数组
import java.util.Random;
import Prog1Tools.IOTools;
public class BinaryMap {
public static void main(String[] args) {
boolean[][] array = generateRandomArray();
//  for (int i = 0; i < array.length; i++) {
//     printArray(array[i]);
// }
}
private static void printArray(boolean[] booleans) {
}
/**
* Ändert einen Wert im gegebenen daten-Array;
* aus wahr wird falsch und aus falsch wird wahr
*
* @param daten - Array welches verändert werden soll
* @param x     - x-Koordinate des Wertes
* @param y     - y-Koordinate des Wertes
*/
static void updateArray(boolean[][] daten, int x, int y) {
}
private static boolean[][] generateRandomArrayFix() {
// Random rand = new Random();
/*
* 10 random aus 100
*/
boolean[][] randomArray;
int x = 10, y = 10;
randomArray = new boolean[x][y];
for (x = 0; x < randomArray.length; x++) {
for (y = 0; y < randomArray.length; y++) {
randomArray[x][y] = false;
}
}
return randomArray;
}
private static boolean[][] generateRandomArray() {
Random rand = new Random();
int rowWidth = IOTools.readInt("Enter Grid Width: ");
int colHeight = IOTools.readInt("Enter Grid Height: ");
boolean[][] board = new boolean[rowWidth][colHeight];
for (int idx = 1; idx <= 10; ++idx) {
//fill the grid
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = rand.nextBoolean();
}
}
//display output
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
//System.out.println();
}
System.out.println();
}
return board;
}
return board;
}
}

欢迎使用SO。不幸的是,您发布的代码有很多问题(包括语法错误(,因此我们很难建议具体的更改来解决您的问题。

与其为需求提供解决方案,我建议您首先将任务分解为几个步骤,并将每个步骤转化为一种方法,在进入下一个步骤之前进行验证(通过单元测试(。

例如,第一个任务是:创建一个初始化为false的10x10数组。为此编写测试可能是唯一棘手的部分。类似于:

class BinaryMap {
public int countValues(boolean value) {
...
}
}
class BinaryMapTest {
@Test
void testInitialisation() {
BinaryMap map = new BinaryMap():
assertThat(map.countValues(false)).isEqualTo(100);
assertThat(map.countValues(true)).isEqualTo(0);
}
}

我建议您在继续随机分配true值之前先让代码正常工作。

在这种情况下,真正需要避免的唯一棘手的事情就是生成10个随机位置并将其分配给true。如果您碰巧生成重复项,那么数组中的true值将少于10个。

所以不是:

for 10 iterations
assign random value to true

你需要

while there are less than 10 true values
assign random value to true

最新更新