Comparar atributos usando CompareTo,
Publicado por Pedro (2 intervenciones) el 12/09/2019 16:59:14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void main(String args[]) {
String[] colores= {"AZUL","AMARILLO","CAFE","PURPURA","ROSA"};
String[] tapa={"SI","NO"};
int grosor;
Random rand = new Random();
for(int i=0; i<100;i++) {
int n =rand.nextInt(5);
int z =rand.nextInt(2);
grosor=(rand.nextInt(5-1+1)+1);
String m= colores[n];
String j=tapa[z];
System.out.println(" COLOR: " + m +""+" \n TAPA:"+j+"\n GROSOR:"+grosor+"\n");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import java.util.Arrays;
import java.util.Random;
public class Marcador {
static class ordenador implements Comparable <ordenador> {
private final String color;
private final String tapa;
private final int grosor;
public ordenador(String color,String tapa,int grosor){
this.color=color;
this.tapa=tapa;
this.grosor=grosor;
}
@Override
public int compareTo(ordenador o){
if (color.compareTo(o.color)<0)
return 1;
else if(color.compareTo(o.color)>0)
return -1;
else
return 0;
}
static void imprimeArraycolores(ordenador[] array){
Random rand = new Random();
for(int i=0; i<10;i++) {
int n =rand.nextInt(4);
System.out.println((i+1)+"."+array[i].color);
}
}
public static void main(String[] args) {
String[] colores= {"AZUL","AMARILLO","CAFE","PURPURA"};
System.out.println("SIN ORDENAR");
imprimeArraycolores(colores);
Arrays.sort(colores);
System.out.println("CON ORDEN");
imprimeArraycolores(colores);
}
}
}
Valora esta pregunta


0