簡體   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