2016-12-14 1 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];