2016-12-02 2 views
1

Ich muss ein 2D-Array mit Zahlen zwischen 2 und 6 füllen, die vom Benutzer angegeben werden (ist nur Teil eines größeren Projekts), aber wenn ich die Nummer gebe, bekomme ich nur eine weitere Anfrage eine Zahl.Zufälliges Füllen eines 2D-Arrays (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; 
    } 

Ich würde wirklich etwas Hilfe schätzen, weil ich weiß nicht, wie, Dank fortzusetzen.

+0

Bitte hängen Sie einen Debugger an und finden Sie es selbst heraus. "Warum funktioniert dieser Code nicht?" Ist Off-Topic auf SO: http://stackoverflow.com/help/how-to-ask – Vampire

Antwort

0

Sie rufen numeroColores() in einer for-Schleife in einer for-Schleife, so dass Sie natürlich mehrere Male dafür gefragt werden.

Btw. Sie haben eine Endlosschleife, wenn Sie in 1 oder kleiner oder 7 oder größer, mit ständig der gleichen Zeile ausgedruckt bekommen und nicht fragen, für neue Eingabe

+0

nun, das war das Problem, danke, jetzt funktioniert es: D –

+0

Dann lesen Sie bitte und folgen http://stackoverflow.com/help/someone-answers – Vampire

0

Versuchen Sie diesen Code geben Sie den zufälligen Wert zwischen 2 und 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; 
} 
zu erzeugen