2016-12-14 54 views
0

我製作了一個隨機填充的二維數組,其中數字介於0和用戶選擇的數字(最大6)之間。我想用顏色來改變這些數字,但是當我嘗試將每個值賦給一種顏色時,我得到的消息是我無法從int轉換爲顏色......任何推薦?因爲我真的被卡住了Integer Value to Color(JAVA)

public static void rellenarTablero(int[][] tablero) { 
    System.out.println("Introduzca el numero de colores (de 2 a 6): "); 
    Scanner in = new Scanner(System.in); 
    int colores = in.nextInt(); 
    while(colores<2||colores>6){ 
     System.out.println("Elija un numero valido:"); 
     colores = in.nextInt(); 
    } 
    for (int x = 0; x < tablero.length; x++) { 
     for (int y = 0; y < tablero[x].length; y++) { 
      tablero[x][y] =1+(int)(Math.random()*(colores)); 
      if(x==1){ 
       x=Color.BLUE; 
      }if(y==1){ 
       y=Color.BLUE; 
      } 
      if(x==2){ 
       x=Color.RED; 
      } 
      if(y==2){ 
       y=Color.RED; 
      } 
      if(x==3){ 
       x=Color.GREEN; 
      } 
      if(y==3){ 
       y=Color.GREEN; 
      } 
     } 
    } 
} 
+1

這些數字應該如何轉換爲顏色?例如,如果用戶輸入3,那麼會導致什麼顏色? – Jesper

+1

您可以從一個Map 'map ... – Tom

+0

開始,這個賦值是無關緊要的,讓我們把1 =藍色,2 =紅色和3 =綠色作爲這個例子,代碼在編輯中,對不起 –

回答

0

如果我理解正確,這應該修復你的代碼。我插入了關於我所做的最重要更改的評論。

// if the table is to be filled with colors, declare it an table of Color 
public static void rellenarTablero(Color[][] tablero) { 
    System.out.println("Introduzca el numero de colores (de 2 a 6): "); 
    Scanner in = new Scanner(System.in); 
    int colores = in.nextInt(); 
    while (colores < 2 || colores > 6) { 
     System.out.println("Elija un numero valido:"); 
     colores = in.nextInt(); 
    } 
    // I prefer to use a Random object for random integers, it’s a matter of taste 
    Random rand = new Random(); 
    for (int x = 0; x < tablero.length; x++) { 
     for (int y = 0; y < tablero[x].length; y++) { 
      int numeroAleatorioDeColor = 1 + rand.nextInt(3); 
      // prefer if-else to make sure exactly one case is chosen 
      if (numeroAleatorioDeColor == 1) { 
       // fill the color into the table (not the int) 
       tablero[x][y] = Color.BLUE; 
      } 
      else if (numeroAleatorioDeColor == 2) { 
       tablero[x][y] = Color.RED; 
      } 
      else if (numeroAleatorioDeColor == 3) { 
       tablero[x][y] = Color.GREEN; 
      } 
      else { 
       System.err.println("Error interno " + numeroAleatorioDeColor); 
      } 
     } 
    } 
} 

它可能會更容易把所有你從進入從一開始一個單獨的數組來選擇顏色:

static final Color[] todosColores = { Color.BLUE, Color.RED, Color.GREEN, Color.YELLOW, Color.BLACK, Color.ORANGE }; 

如果你有很多顏色可供選擇,這一點尤其如此。現在你可以做的只是:

  // number to use for array index; should start from 0, so don’t add 1 
      int numeroAleatorioDeColor = rand.nextInt(todosColores.length); 
      tablero[x][y] = todosColores[numeroAleatorioDeColor];