2016-12-14 3 views
0

0からユーザーが選択した数値(最大6)でランダムに塗りつぶされた2D配列を作成しました。これらの数値を色で変更したいのですが、各値を色に割り当てようとすると、intからcolorに変換できないというメッセージが表示されます...どのような勧告ですか?私が本当につまらないので整数値(色)

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 'マップで始めることができます。 – 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];