2016-12-02 72 views
1

我需要用2到6之間的數字填充2D數組,這是用戶給出的(只是一個更大的項目的一部分),但是當我給出數字時,我只能獲得另一個請求一個號碼。隨機填充一個二維數組(Java)

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

我真的很感激一些幫助,因爲我不知道如何繼續,謝謝。

+0

請附上一個調試器,並找出你自己。 「爲什麼不是這個代碼工作」是關於SO的外部主題:http://stackoverflow.com/help/how-to-ask – Vampire

回答

0

您在for循環中的for循環中調用numeroColores(),因此您當然會多次詢問它。

Btw。你有無限循環,如果你在1或更小或7或更大的用不斷得到相同的線打印出來,並沒有要求新的輸入

+0

好吧,這是問題,謝謝,現在它的工作:D –

+0

然後請閱讀並按照http://stackoverflow.com/help/someone-answers – Vampire

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