繁体   English   中英

随机填充2D数组(Java)

[英]Randomly fill a 2D array (Java)

我需要填充一个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;
    }

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

你在for循环中的for循环中调用numeroColores() ,所以你当然会多次询问它。

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

尝试使用此代码生成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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM