| 1 | import java.awt.Color; |
| 2 | import java.util.List; |
| 3 | import java.util.Arrays; |
| 4 | |
| 5 | public class Eye implements Comparable<Eye> { |
| 6 | private Color color; |
| 7 | private List<String> colorList = Arrays.asList("black", "green", "blue", "brown"); |
| 8 | |
| 9 | Eye(String color) { |
| 10 | setColor(color); |
| 11 | } |
| 12 | |
| 13 | public Color getColor() { |
| 14 | return color; |
| 15 | } |
| 16 | |
| 17 | public void setColor(String color) { |
| 18 | if (validateColor(color)) { |
| 19 | if (color.equals("brown")) |
| 20 | this.color = new Color(88, 41, 0); |
| 21 | else |
| 22 | this.color = Color.getColor(color); |
| 23 | |
| 24 | } else { |
| 25 | throw new IllegalArgumentException("Color must be " + colorList.toString()); |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | private boolean validateColor(String color) { |
| 30 | return colorList.contains(color); |
| 31 | } |
| 32 | |
| 33 | @Override |
| 34 | public int compareTo(Eye eye) { |
| 35 | double r_diff = this.getColor().getRed() - eye.getColor().getRed(); |
| 36 | double g_diff = this.getColor().getGreen() - eye.getColor().getGreen(); |
| 37 | double b_diff = this.getColor().getBlue() - eye.getColor().getBlue(); |
| 38 | // See https://en.wikipedia.org/wiki/Color_difference |
| 39 | Double distance = Math.sqrt(2 * Math.pow(r_diff, 2) + 4 * Math.pow(g_diff, 2) + 3 * Math.pow(b_diff, 2)); |
| 40 | return distance.intValue(); |
| 41 | } |
| 42 | } |