java - 随机填充二维数组(Java)

标签 java arrays random 2d

我需要用用户给出的 2 到 6 之间的数字填充一个 2D 数组(只是更大项目的一部分),但是当我给出该数字时,我只会收到另一个对数字的请求。

public static int[][] crearTablero(int tamaño)
{
    int[][] tablero = new int[tamaño][tamaño];
    return tablero;
}
public static void imprimeTablero(int[][] tablero)
{
    for(int i = 0; i<tablero.length; i++)
    {
        for(int j = 0; j<tablero[i].length; j++)
        {
            System.out.print(tablero[i][j] + " ");
        }
        System.out.println();
    }
}
public static void swap(int[][] tablero, int x1, int y1, int x2, int y2)
{
    int temp = tablero[x1][y1];
    tablero[x1][y1] = tablero[x2][y2];
    tablero[x2][y2] = temp;
}
public static void rellenarTablero(int[][] tablero) {
    for (int x = 0; x < tablero.length; x++) {
        for (int y = 0; y < tablero[x].length; y++) {
            tablero[x][y] = aleatorio(numeroColores());
        }
    }
}
public static void shuffleBoard(int[][] tablero)
{
    Random rnd = new Random();
    int randX = 0;
    for(int x = 0; x<tablero.length; x++)
    {
        randX = rnd.nextInt(tablero.length);
        int[] temp = tablero[x];
        tablero[x] = tablero[randX];
        tablero[randX] = temp;
    }
}
public static int numeroColores(){
    int colores = 0;
    System.out.print("Numero de colores (entre 2 y 6): ");
    Scanner scn = new Scanner(System.in);
    colores = scn.nextInt();
    while(colores < 2 || colores > 6)
    {
        System.out.println("Invalid matrix size. Re-enter ");
    }
    return colores;
}
public static int aleatorio(int colores) {
    int l = (int) (Math.floor(Math.random()*(colores-2)) + 2);
    return l;
    }

我真的很感激一些帮助,因为我不知道如何继续,谢谢。

最佳答案

您在 for 循环中调用 numeroColores(),因此您当然会被多次询问。

顺便说一句。如果您输入 1 或更小或 7 或更大,并且不断打印出同一行并且不要求新输入,则会出现无限循环

关于java - 随机填充二维数组(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40933518/

相关文章:

java - 从 java : Why doesn't the array get printed? 传递的 c 中打印数组

java - 在Java中递归生成随机对象

mysql - 为什么 MySQL Rand() 讨厌我?

c++ - RAND_MAX 和 UINT_MAX 之间的差异会有所不同吗?

java - 在项目中添加Java代码模板XML文件

java - 控制台输出流的类型

javascript当null时跳转到下一条记录代码修改

java - 使用 GSON 在字符串和 byte[] 之间转换 JSON

java - 创建一个表来存储单行是糟糕编程的标志吗?

php - 字符串的键和索引 - 内爆