vendredi 2 décembre 2016

Randomly fill a 2D array (Java)

Well i´ve been working for a while and i can't found where i have failed, I need to fill a 2D Array with numbers between 2 and 6, given by the user (is just part of a bigger proyect) but when I give the number I only get another request for a number... so...

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

I would really apreciate some help because I don't know how to continue, Thanks.




Aucun commentaire:

Enregistrer un commentaire