Valeur entière à la couleur (JAVA)
J'ai fait un tableau 2D rempli aléatoirement avec des nombres entre 0 et un nombre sélectionné par l'utilisateur (max 6). Je voudrais changer ces nombres avec des couleurs, mais lorsque j'essaie d'attribuer chaque valeur à une couleur, je reçois le message que je ne peux pas convertir de int en couleur... Tout recomendation? parce que je suis vraiment coincé
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;
}
}
}
}
0
Author: Sergio Hernandez, 2016-12-14
1 answers
Si je comprends bien, cela devrait corriger votre code. J'ai inséré des commentaires sur les modifications les plus importantes que j'ai apportées.
// 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);
}
}
}
}
Il peut être plus facile de mettre toutes les couleurs que vous devez choisir dans un tableau séparé dès le début:
static final Color[] todosColores = { Color.BLUE, Color.RED, Color.GREEN, Color.YELLOW, Color.BLACK, Color.ORANGE };
Ceci est particulièrement vrai si vous avez beaucoup de couleurs à choisir. Maintenant, vous pouvez faire juste:
// 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];
0
Author: Ole V.V., 2016-12-14 13:10:15