整数值到颜色(JAVA)

时间:2016-12-14 12:06:04

标签: java arrays colors assign

我随机填充了一个2D数组,数字介于0和用户选择的数字之间(最多6)。我想用颜色更改这些数字,但是当我尝试将每个值分配给一个颜色时,我得到的消息是我无法从int转换为颜色......任何推荐?因为我真的卡住了

    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 个答案:

答案 0 :(得分: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];