随机填充2D数组(Java)

时间:2016-12-02 13:38:20

标签: java arrays random 2d

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

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;
    }

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

2 个答案:

答案 0 :(得分:0)

您在for循环中的for循环中调用var hideFilters = function() { var listCategoryId = ['1000014', '1000015', '1000016', '1000017', '1000018', '1000019', '1000021', '1000086']; var actualCategoryId = '1000018'; if (actualCategoryId === listCategoryId) { console.log('is equal'); } else { console.log('fuen... fuen...'); } }; hideFilters(); ,因此您当然会多次询问它。

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

答案 1 :(得分:0)

尝试使用此代码生成2到6之间的随机值

public static int aleatorio(int colores) {
    int l = 0;
    while(l < 2 || l > 6) {
        l = (int) (Math.floor(Math.random()*(colores-2)) + 2);
    } 
    return l;
}